1
\$\begingroup\$

I've written a custom Error handler for use in PHP. What it does is simply capture PHP errors, and logs them using Monolog.

It works, but I can't help that it has too much stuff inside. I could remove the error levels that are not handled by set_error_handler but that's guaranteed to lead to a developer that spends 2 hours wondering "why E_ERRORs are not getting logged"...

Could this function be improved somehow?

set_error_handler(function($errno ,$errstr,$errfile ,$errline, $errcontext) {
    // When we use the error supressing operator (@) 
    // error_reporting is temporarily set to 0
    // Do not log anything for that case
    if(ini_get('error_reporting')==0){return;}


    $halt = FALSE;
    // http://php.net/manual/en/errorfunc.constants.php
    switch($errno){
        case E_USER_ERROR:
        case E_RECOVERABLE_ERROR:
            $halt = true;
            $logType = 'error';
            break;

        case E_WARNING:
        case E_USER_WARNING:
        case E_STRICT:
        case E_DEPRECATED:
            $logType = 'warning';
            break;

        case E_NOTICE:
        case E_USER_NOTICE:
            $logType = 'notice';
            break;

            // The following error types cannot be caught by set_error_handler
            // Adding them for reference only
        case E_CORE_WARNING:
        case E_COMPILE_ERROR:
        case E_COMPILE_WARNING:
        case E_CORE_ERROR:
        case E_ERROR:
        case E_PARSE:
            return FALSE;

        // We should never reach this case. But you never know
        case E_ALL:
        default:
            $logType = 'warning';
    }
    Logger::{$logType}($errstr, $errcontext);
    // Halt the execution for errors that should halt
    if($halt)
        exit($errno);
});
\$\endgroup\$
0
\$\begingroup\$

Look here it is already tested on live projects error catcher.

Fatal errors can be catch only by 'register_shutdown_function'

You do not track uncatched Exceptions, it can be done by 'set_exception_handler'

If code runout all memory it will not able to log error, but it you does not catch Fatal errors so it is not your case.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.