Trigger error from exception handler

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

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

      

The idea is to use an existing error handler to handle the exception to avoid repeating the same code. Is throwing an error inside an exception handler causing some problems?

+2


source to share


2 answers


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

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



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 is sending an HTML email, I have html in my exception handler. You can remove this.

+1


source


I've seen errors and exceptions mixed up in PHP code before. While this should not technically cause any problems, it is likely to create confusion for the developers maintaining the code. If you have time, consider refactoring all trigger_error code to use exceptions instead. Sure, you're stuck with any trigger_error stuff made by PHP itself, but hopefully you can avoid most of these situations.



+1


source







All Articles