Richard Richard - 1 month ago 5
PHP Question

Get error before they execute the error message function

I want to receive the error message in php before it gets executed. Basicly what i mean is that if I would have a bad code:

// This code is incorrect, I want to receive the error before it gets handled!
$some_var = new this_class_is_not_made;


Now that class does not exist, so it would be handles by the default error handler in php. But I want to disable the normal error handler and create my own.

Another example:

somefunction( string some_var ); // some_var misses the variable prefix. ( $ )


Example error message:


Fatal error: function 'some_var' is not defined in line: $x!


And this error would be:
somefunction( string some_var );


But how would I receive the messages but also disable the normal error system?

EDIT: Making the error system execute a
user-defined
function

// I would want the error system to execute a function like this:
function(string $errorMessage, int $error_code){
if($error_code < 253){ return "Fatal error"; }
if($error_code < 528 && $error_code > 253){ return "Warning"; }
}


Answer found: By: ShiraNai7

try
{
// Code that may throw an Exception or Error.
}
catch (Throwable $t)
{
// Executed only in PHP 7, will not match in PHP 5
}
catch (Exception $e)
{
// Executed only in PHP 5, will not be reached in PHP 7
}

Answer

In PHP 7.0.0 or newer the code will throw Error exception if this_class_is_not_made doesn't exist.

try {
    $some_var = new this_class_is_not_made;
} catch (Error $e) {
    echo $e->getMessage();
}

Note that that this will also catch any other Error exceptions in case this_class_is_not_made does exist and causes some other error along the way.

In PHP versions prior to 7.0.0 you're out of luck - fatal errors always terminate the main script.

It might be a better idea to use class_exists() instead:

if (class_exists('this_class_is_not_made')) {
    $some_var = new this_class_is_not_made;
}

This works in all PHP versions that support classes.

Comments