Marc Ermshaus’ avatar

Marc Ermshaus

Linkblog

PHP Snippet: Custom error handler

Published on 8 Oct 2010. Tagged with php.

<?php

class ErrorController
{
    public function errorAction(Exception $exception)
    {
        echo '<h2>There was an error</h2>'
           . '<pre>' . $exception . '</pre>';
    }
}

$err = new ErrorController();

// Reroute all errors to our controller
set_exception_handler(array($err, 'errorAction'));
set_error_handler(
    function ($errno, $errstr, $errfile, $errline, array $errcontext = null)
    {
        throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
    });



// Let's test it out

error_reporting(-1);

try {
    throw new Exception('Gonna catch this');
} catch (Exception $e) {
    // Catching errors works in the normal way
}

// Test 1 (default exception, comment the following line to enable Test 2)
throw new Exception('Something went wrong');

// Test 2 (default warning, will be transformed to an Exception and handled by
//         the controller)
echo 1/0;