Sign In or Create Account

Huge image

Handling Errors in PHP 5

Posted on Feb 08, 2010 by Andrei

This class could be helful in case you have no error/exception handling code and believe you have absolute test coverage for every single component of your site ;) Just add Ns_ErrorHandler::setHandlers() to your bootrap file and who knows, maybe there's actually something you've missed.

class Ns_ErrorHandler
{
    /**
     * @var array
     */
    private static $_ignoredErrors = array(8, 2048, 8192, 16384); // E_NOTICE, E_STRICT, E_DEPRECATED, E_USER_DEPRECATED
    
    /**
     * @var array
     */
    private static $_fatalErrors = array(1, 256); // E_ERROR, E_USER_ERROR

    /**
     * Sets error handlers
     */
    public static function setHandlers()
    {
        set_error_handler(array(__CLASS__, 'handleError'));
        set_exception_handler(array(__CLASS__, 'handleException'));
        register_shutdown_function(array(__CLASS__, 'shutdown'));        
    }
    
    /**
     * Handles PHP errors
     *
     * @param int    $errno
     * @param string $error
     * @param string $errfile
     * @param string $errline
     */
    public static function handleError($errno, $errstr, $errfile, $errline)
    {
        // Ignore error?
        if (in_array($errno, self::$_ignoredErrors)) {
            return;
        }

        // Send email
        $errorString = "{$errno}: {$errstr} in {$errfile} on line {$errline}";
		mail('notify@this.address', 'Error', $errorString);
		
		// Display eror page
		if (in_array($errno, self::$_fatalErrors)) {
			@ob_end_clean();
			self::_showErrorPage();
		}
    }
    
    /**
     * Handles Exception
     *
     * @param Exception $e
     */
    public static function handleException(Exception $e)
    {
		// Send email
		mail('notify@this.address', 'Error', print_r($e, true));
		
		// Display erro page
		@ob_end_clean();
		self::_showErrorPage();
    }
    
    /**
     * Using shutdown function we can catch fatal errors
     * which don't go through error_handler
     */
    public static function shutdown()
    {
        if ($err = error_get_last()) {
            call_user_func_array(array(__CLASS__, 'handleError'), array_values($values));
        }
    }
	
	private static function _showErrorPage()
	{
		// show some html here
	}
}

// Set handlers
Ns_ErrorHandler::setHandlers();

Questions?




Tags:

Oops. No tags.


Comments:


Name:
Email: (won't be dispayed anywhere on the site)
URL:
Comment: