Handling Fatal Errors in PHP

Yesterday, I went over the ways to use a debug class in order to catch and report exceptions. Today, I will build off that same class we used to catch and show fatal errors as well as keeping the display of the notice stack. We will do this by using the php function register_shutdown_function, and passing the current class instance. This is done in a similar fashion to how we handled exceptions. But, first things first – we need to build the helper functions that we will use while handling the errors.

First, we want a quick way to change the error[‘type’] into text that we can output. For that, we’ll create the method called ‘getErrorType’ which will take a numeric input and return the string equivalent to it.

Notice that it is declared in the private scope. We do this as this class is meant to be the say-all in the debugging process, so no other class/method/code should need to call it from outside of our debug class.

Next, we create a method that will be called on script ‘shutdown’.

Now, that method will call our error handler if ANYTHING has gone wrong in the script before it is killed. Notice the comments stating that it is blanketing everything. If you want to change the handler to only call the stack on a fatal error, check for $e['type'] == 1 , rather than $e != null .

Now that our new helper methods have been created, we’ll go back in to the __construct() method and add a few things. First, we want to stop PHP from displaying errors itself, that’s the purpose of this class, so we’ll add the line ini_set('display_errors', 0); to the top of our constructor, and then we’ll register the shutdown handler that we just created with register_shutdown_function(array($this, "handleShutdown")); Notice the context – it is called every time a script ends, but before objects are dismantled – which is why we check for an error rather than routing it immediately to our error method. So now, our full constructor method looks like:

And now, your debug class can catch and close nicely when a fatal error appears – showing in the same format as we had for exceptions yesterday, but adding the fatal error as the error message instead of the exception thrown.

No Comments Yet


There are no comments yet. You could be the first!

Leave a Comment

    Search the Blog