Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: set_exception_handler not working for error thrown in set_error_handler callback

Tags:

exception

php

I have the following code to setup my error/exception handlers:

// Set the exception handler
set_exception_handler(function($e) {
    echo 'Exception';
});

// Set the error handler
set_error_handler(function($code, $message, $file, $line) {
    throw new ErrorException($message, 0, $code, $file, $line);
});

I have read numerous articles which have said to throw an exception within the set_error_handler callback function. This should mean I only have to handle exceptions. However the set_exception_handler callback function is never called and instead I get the warning:

Warning: Uncaught exception 'ErrorException' with message...

Please note that I am using PHP 5.4.

like image 406
nfplee Avatar asked May 14 '26 18:05

nfplee


1 Answers

I tried to run the PHP script below, and it runs fine.

// set the exception handler
set_exception_handler(function($e) {
  echo ' Exception';
});

// set the error handler
set_error_handler(function($code, $message, $file, $line) {
  echo " Error [$message]";
  throw new ErrorException($message, 0, $code, $file, $line);
},-1);

// trigger error
trigger_error('My own error.',E_USER_ERROR);

It returns:

Error [My own error.] Exception

Its exactly the same as yours. I cannot find anything wrong with the piece of code you provided, could the problem be outside it?

like image 100
KIKO Software Avatar answered May 17 '26 08:05

KIKO Software



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!