简体   繁体   中英

Custom PHP Error Handler with Alert

I would like to launch a JavaScript alert box with all PHP error information inside. I've managed to use PHP's set_error_handler(), but it keeps launching the default error and it's not letting me select other possibilities.

set_error_handler(custom_error_handler());

function custom_error_handler($errno, $string, $file, $line)
{
    switch ($errno)
    {
        case E_ERROR:
        case E_USER_ERROR:
            echo "ERROR";
        break;

        case E_WARNING:
        case E_USER_WARNING:
            echo "WARNING";
        break;

        case E_NOTICE:
        case E_USER_NOTICE:
        case E_DEPRECATED:
        case E_USER_DEPRECATED:
        case E_STRICT:
            echo "NOTICE";
        break;

        default:
            echo "WTF?";
        break;
    }

    return true;
}

ini_set("display_errors", "0");
error_reporting(E_ALL);

trigger_error("Hello, Error!", E_USER_NOTICE);

This error handler of yours only shows a Javascript error in case there is an error of a type that is not covered by your switch case statement. Since you raise an E_USER_NOTICE, you just get the text 'NOTICE' as output of the page, which is obviously not shows in an alert.

Furthermore, as R. Barzell mentioned in his answer, you should omit the parentheses after custom_error_handler) when registering the error handler. Apart from that, you might need to call set_error_handler(custom_error_handler); after declaring the function 'custom_error_handler'.

Remove the () from "custom_error_handler" within your set_error_handler call. As in:

set_error_handler(custom_error_handler);

The () at the end of the inner function actually evaluates it, rather than sets it as a callback.

Any time you want to pass a function to another function, don't use (). Only add that if you want the function to be evaluated, and its result passed into the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM