Josh

I'm a developer in Melbourne, Australia, and co-founder of Hello Code.

Published Sun 11 November 2007

← Home

Turning PHP errors into Exceptions

I've just been browsing the PHP6 meeting minutes to see if anything exciting is coming up in the next release. There are a couple of handy things which I might post about soon, but in the meantime this useful code snippet caught my eye. I wasn't aware you could handle errors yourself in PHP5, but it seems it is possible to do so. The following catches all errors of level E_NOTICE and throws an exception instead. Pretty handy if you already use Exceptions for your own errors — now you can decide what to do with parser errors, instead of being forced into displaying them or just ignoring them.

The code:

<?php
    function error_handler($errorType, $message){
            if ($errorType == E_NOTICE) {
                    throw new Exception( $message, $errorType);
            }
    }

    set_error_handler('error_handler');
?>
To top