PHPException handling is all well and good in PHP, try/catch blocks work pretty nice for the most part, but annoyingly enough, these don’t deal, or ‘catch’, non exception cases like E_WARNINGs or E_NOTICEs at all.

So how does one deal with them then?

Well the answer is to use PHP’s set_error_handler functionality, essentially pointing the engine to direct any error to a particular custom built function.

In PHP 5.0 and later, you can specify which error to trap by directly naming it in your set_error_handler call. So for example, to trap an E_WARNING notice, you would insert at the top of your script the following code:

set_error_handler(“custom_warning_handler”, E_WARNING);

function custom_warning_handler($errno, $errstr) {
// do something
}

In PHP 4.x, you can do it in more or less the same manner, but you do need to add an extra step in because it is now up to you to filter out the E_WARNING type:

(Note that by returning true you indicate that you have handled the error. Returning false pushes you back to the normal, default error handler)

set_error_handler(“custom_warning_handler”);

function custom_warning_handler($errno, $errstr) {
switch ($errno) {
case E_WARNING:
// do something
return true;
break;
default:
return false;
break;
}
}

Related link: http://php.net/set_error_handler