Friday, January 29, 2010

Dealing fatal errors in PHP

When a fatal error in PHP occurs, the flow of the program halts resulting in a blank screen or a system error message. Leaving your end-users confused and you, as the programmer, unaware that these fatal errors might be occuring.

RawDev offers a simple way to handle fatal errors more gracefully so that you can (a) log/email the error and (b) display an appropriate message and a path to continue so that the end-user is not staring at a system message or worse, a blank screen unsure what to do next.


How it works

PHP displays the fatal error right before it halts. RawDev reads the output buffer and detects when a fatal error occurs. That's when it calls your custom handler.

Basically all you have to do is register a fatal error handler. See example below.

Example


RFatal::setHandler('fatalErrorHandler');

hello(); # since this function does not exist it will throw a fatal error

# this area is never reached because you get a handle, but PHP is going to halt anyways

RFatal::unsetHandler(); #optional function to remove the fatal error handler

?>

Display Errors


Note that display_errors needs to be set for the RFatal class to work, which is the default in PHP. Usually this config parameter is set by the sysadmin in the php.ini file. Sometimes (typically in production) this is turned off for security reasons with non-favorable usability impact. In RawDev this needs to be turned on. The security issue no longer applies because an appropriate message to the end-user should be displayed by you, the programmer, in the fatal error handler. Typically something similar to a 404 with a simple message and a path to continue.



Conclusion

By trapping the output buffering you can actually get a handle to fatal errors, and RawDev makes it easy to do this. There are cases where you do not want to do output buffering, for example when dealing with very large output. In that case, don't use fatal error trapping.



Links

API Doc for RFatal

No comments:

Post a Comment