2

Given that I have a custom PHP error handler already, does it make sense to define an exception handler as an "forwarder" like this:

function exception_handler(Exception $e) {
    trigger_error($e->getMessage(), E_USER_ERROR);
}
set_exception_handler('exception_handler');

The idea is to utilize the already existing error handler to handle exception too, to avoid repeating the same code. Does triggering an error from inside an exception handler cause some problems?

2 Answers 2

1

No problem with it at all. I have the same setup, my error handler emails me with exceptions as well as errors.

Here is my exception handler, I put in the error that I have an uncaught exception. This way I know that it was caused by an exception and not an error. It also will tell me the exception because of the get_class.

function exception_handler(Exception $e) {
  trigger_error('Uncaught ' . get_class($e) . ', code: ' . $e->getCode() . "<br/>\n Message: " . htmlentities($e->getMessage()), E_USER_WARNING);
}

Since my error handler sends an HTML email I have html in the exception handler. You may want to remove that.

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

Comments

1

I've seen errors and exceptions mixed in PHP code before. While technically it shouldn't cause any problems, it will likely create confusion for developers maintaining the code. If you have the time, consider refactoring all your trigger_error code to use exceptions instead. Of course you're stuck with any trigger_error stuff that PHP itself is creating but hopefully you can avoid most of those situations.

3 Comments

Exceptions and Errors are separate things. I do agree you could refactor any trigger_error calls into exceptions but this won't handle the built in errors which you can not remove. Like you said. :)
Ah, of course it could be done this way too (making error handler to throw exceptions, instead of exception handler triggering errors). But I wonder which way is preferable, and why?
Since Exceptions only take one parameter and Errors take multiple parameters it would be easier the OPs way.

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.