PHP: can anyone explain this Exception Handler error? - php

hi can anyone here can help how to determine whats the error on here? please i really need to know. thank you in advance guys! help me to figure out what is wrong with the codes below.
function exception_error_handler($errno, $errstir, $errfile, $errline ) {
throw new ErrorException($errstr, $errno, 0, $errfile, $errline);;
}
set_error_handler("exception_error_handler");
/* Trigger exception */
strpos();
i don't know whats the error on this but it stills keeping an error output. pls help me guys

In PHP notices and warnings don't throw exceptions. Calling strpos() without parameters is a warning. That function registers your custom function as the error_handler, which basically converts all notices and warnings to an exception. It' useful for development and debugging, and a lot of frameworks use something like that to show error pages in development mode.

Could you try the following code which catches the custom ErrorException which you throw?:
function exception_error_handler($errno, $errstir, $errfile, $errline ) {
throw new ErrorException($errstr, $errno, 0, $errfile, $errline);;
}
set_error_handler("exception_error_handler");
try {
/* Trigger exception */
strpos();
echo 'No exception was thrown';
}
//catch exception
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}

Related

Unable to catch Exception when using Eval function

I'm writing code that randomly generates expressions for a genetic algorithm for code optimisation purposes. The generated expressions are eval'ed for fitness. Some expressions will generate errors and I need to be able to catch these and act appropriately.
I have the following code (simplified from the original):
set_error_handler(function($errno, $errstr, $errfile, $errline, $errcontext) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
});
$expression = '$y=~!7;';
try {
eval($expression);
} catch (Exception $e){
echo 'Expression failed';
} catch (ParseError $e){
echo 'Expression failed';
}
This throws the following error:
PHP Fatal error: Unsupported operand types in ..... : eval()'d code on line ....
But this error is not caught in either catch block.
I've set my own error handler so that all errors are promoted to exceptions.
How do I catch this error?
Note: I am very aware that using eval is dangerous, but there is strictly no user input in my code.
At least in PHP 7.1+, eval() terminates the script if the evaluated code generate a fatal error. For example:
#eval('$content = (100 - );');
(Even if it is in the man, I'm note sure it acted like this in 5.6, but whatever)
To catch it, I had to do:
try {
eval('$content = (100 - );');
} catch (ParseError $e) {
$content = null;
}
This is the only way I found to catch the error and hide the fact there was one.

How to catch "No error: PDO constructor was not called"

how can I catch the following error: No error: PDO constructor was not called?
My question is not how to solve the error, but how to catch it!
I need that for a PHPUnit Testing Environment.
I was trying to catch it like that, but it simply doesn't work that way.
$pdo = (new \ReflectionClass(\PDO::class))->newInstanceWithoutConstructor();
try
{
$pdo->query("SELECT * FROM table");
}
catch (ErrorException $exc)
{
echo $exc->getTraceAsString();
}
the exact (error) message is as follows: PDO::query(): SQLSTATE[00000]: No error: PDO constructor was not called, but I am not sure, if that is even any type of PHP catchable.
I've already checked the method pdo_raise_impl_error()[PHP 7.3.3] that is called with the mentioned error message, but I am not wise enough to anticipate what actual type of error it produces...
Can please someone give advise?
Not sure if it's a solution you are looking for, but you can always convert all errors to exceptions with as simple code as
set_error_handler(function ($level, $message, $file = '', $line = 0)
{
throw new ErrorException($message, 0, $level, $file, $line);
});
Of course it will make a global error handler, but honestly, I believe every PHP project should have a code like this.
Or at least you can call this handler only temporarily
I now use the following code fore my test.
please check the first and the last line of code especially.
thanks to #YourCommonSense!
set_error_handler(function(int $errno, string $errstr, string $errfile, int $errline) {
throw new ErrorException($errstr, $errno, E_ERROR, $errfile, $errline);
});
$this->expectException(ErrorException::class);
$this->expectExceptionMessage("SQLSTATE[00000]: No error: PDO constructor was not called");
/* #var $pdo PDO */
$pdo = (new ReflectionClass(PDO::class))->newInstanceWithoutConstructor();
$pdo->query("SELECT * FROM table"); // triggers the error.
restore_error_handler();

Customizing PHP error messages

I want to change the following PHP error message so that user does not see this error and I would like to display an error which is more understandable by the user.
For example consider this error which I want to edit,
Notice: Undefined index: user_input on line 33
I want to display the following error message instead of the above default error message,
Process failed
How can I implement this on my website?
This is not an error it is a notice, so you will need to do few things:
First look into ErrorException you need to convert the notice to an exception.
Catch the exception
Print your custom error message
Example:
<?php
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");
try {
//Trigger exception:
$my_array = array();
echo $my_array['undefined'];//Notice will throw exception
} catch (Exception $e) {
echo 'Process failed';
}
?>
You should check to see if the variable is set and display the error message you want if it's not

How to get file_get_contents() warning instead of the PHP error?

file_get_contents('https://invalid-certificate.com');
Yields the following PHP warning and error:
PHP warning: Peer certificate CN='*.invalid-certificate.net' did not match expected CN='invalid-certificate.com'
PHP error: file_get_contents(https://invalid-certificate.com): failed to open stream: operation failed
I want to use exceptions instead of the PHP warning, so:
$response = #file_get_contents('https://invalid-certificate.com');
if ($response === false) {
$error = error_get_last();
throw new \Exception($error['message']);
}
But now the exception message is:
file_get_contents(https://invalid-certificate.com): failed to open stream: operation failed
That's normal, error_get_last() returns the last error…
How can I get the warning, which contains much valuable information regarding the failure?
You can make good use of set_error_handler and convert those errors into exceptions and use exceptions properly
<?php
set_error_handler(function($errno, $errstr, $errfile, $errline, array $errcontext) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
});
try {
$response = file_get_contents('https://invalid-certificate.com');
} catch (ErrorException $e) {
var_dump($e); // ofcourse you can just grab the desired info here
}
?>
A much simpler version would be
<?php
set_error_handler(function($errno, $errstr) {
var_dump($errstr);
});
$response = file_get_contents('https://invalid-certificate.com');
?>
Fiddle

PHP Error Logs + Add a Session Value to the log entry

This is most likely a silly question so I have no issues with it being closed etc.
I'm debugging PHP error logs and it would be of great advantage if I could see the user that created the specific error.
The userid is keep in the session.
Is it possible to customize PHP error logs to include a session value for debugging?
thx
Of course it is possible, I don't see why not:
try {
//some code
} catch (Exception $e) {
session_start();
$log = 'Caught exception: '. $e->getMessage(). "\n";
$log .= 'By user = '.$_SESSION['user_id']. "\n";
error_log($log);
}
To change error messages into Exception use this code:
<?php
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");
/* Trigger exception */
strpos();
?>
ErrorException

Categories