Joonas Pulakka
Joonas Pulakka

Reputation: 36577

Trigger error from within exception handler

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?

Upvotes: 2

Views: 504

Answers (2)

MitMaro
MitMaro

Reputation: 5937

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.

Upvotes: 1

Asaph
Asaph

Reputation: 162849

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.

Upvotes: 1

Related Questions