Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I catch ALL errors in PHP?

I've found a lot of attempts at all-inclusive error handling implementations, and I figured I might write up a wiki-style to hopefully provide a complete solution that I came up with.

The question is:

"How might one catch, handle, or intercept ALL error types in PHP?"

Now - this might be deemed a 'rewrite' by some - but I don't know that there's been a comprehensive solution proposed.

like image 654
DigitalJedi805 Avatar asked Feb 15 '26 14:02

DigitalJedi805


1 Answers

There are three kinds of error handlers you need:

  • set_exception_handler, to catch any otherwise uncaught exceptions.

  • set_error_handler to catch "standard" PHP errors. I like to first check it against error_reporting to see if it's an error that should be handled or ignored (I generally ignore Notices - probably bad but that's my choice), and throw an ErrorException, letting the exception handler catch it for outputting.

  • register_shutdown_function combined with error_get_last. Check the value of ['type'] to see if it is E_ERROR, E_PARSE or basically any fatal error types you want to catch. These normally bypass set_error_handler, so catching them here lets you grab them. Again, I tend to just throw an ErrorException, so that all errors end up being handled by the same exception handler.

As for how you implement these, it depends entirely on how your code is set up. I usually do an ob_end_clean() to purge any output, and present a nice error page telling them that the error has been reported.

like image 159
Niet the Dark Absol Avatar answered Feb 17 '26 08:02

Niet the Dark Absol



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!