PHP: How to Catch a Script Warning or Notice CodeUnit 09 SEP 2009

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)


function custom_warning_handler($errno, $errstr) {
switch ($errno) {
// do something
return true;
return false;

Related link:

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.

  • Spam Hater

    Thanks for a great post here.
    It helped me solve an error I was getting with E_WARNING messages.  Now I can just ignore the specific warning then revert back to standard error reporting.