3

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.

1 Answer 1

4

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?

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks your example worked fine. However if you try doing "require 'DoesNotExist.php';" instead of "trigger_error(...);" it will call the error handler but not the exception handler.
PHP manual: "require is identical to include except upon failure it will also produce a fatal E_COMPILE_ERROR level error.", hence the error message because compile errors are issued before the code is executed. Use 'include' to work with the exception handler. There is a way to make it work. Make a php file that is bug-free and 'includes' two other PHP files: 1. Your error handler. 2. The file you want to debug. That way your error handling routines have been executed before the file to debug is being compiled.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.