Custom Error Handlers

The errors produced by PHP are useful when developing scripts, but aren't sufficient for deployment in a web database application. Errors should inform users without confusing them, not expose secure internal information, report details to administrators, and have a look and feel consistent with the application. This section shows you how to add a professional error handler to your application, and also how to improve the internal PHP error handler to produce even more information during development.

If you're not keen to develop a custom handler (or don't want to use ours!), you'll find an excellent class that includes one at http://www.phpclasses.org/browse.html/package/345.

A Basic Custom Handler

To begin, we show you how to implement a simple custom handler. The set_error_handler( ) function allows you to define a custom error handler that replaces the internal PHP handler for non-critical errors:

string set_error_handler(string error_handler )

The function takes one parameter, a user-defined error_handler function that is called whenever an error occurs. On success, the function returns the previously defined error handler function name, which can be saved and restored later with another call to set_error_handler( ). The function returns false on failure.

The custom error handler is not called for the following errors: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, and E_COMPILE WARNING. For these, the PHP internal error handler is always ...

Get Web Database Applications with PHP and MySQL, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.