开发者

exception_handling -> not as robust as simply logging error?

Exception handling in php ... I have noticed some quirks that seem to make it a tedious matter to implement properly. First off, most legacy php functions do not throw exceptions per se, it seems one has to implement set_error_handler and have the callback throw functions. Ok. Minor annoyance but let's see what gives. OH! Great, now everything throws an exception, and of course, the worst part: uncaught exceptions halt the script.

So, kind of got to figure after reading the manual and other posts here, one has to implement set_exception_handler, and also have the set_error_handler callback to not throw on E_NOTICE, E_WARNING.

IS this correct so far? After re-reading the manpage, it 开发者_开发问答seems set_exception_handler halts the script on every error, even recoverable ones with no way for the script to continue.

So this seems a no no for me, I can't have scripts stop executing for notice or event warnings.

Are there workarounds? I'm curious to know how others deal with exceptions and these issues.


This is an exception handler that Larry Ullman wrote in his book PHP 5 Advanced (A great book).
It combats most of what you are saying

function my_error_handler ($e_number, $e_message, $e_file, $e_line, $e_vars)
{
    global $debug, $contact_email;
    $message = "An error occurred in script '$e_file' on line $e_line: \n<BR />$e_message\n<br />";
    $message .= "Date/Time: " . date('n-j-Y H:i:s') . "\n<br />";
    $message .= "<pre>" . print_r ($e_vars, 1) . "</pre>\n<BR />";
    if ($debug)
    {
        echo '<p class="error">'.$message.'</p>';
    }
    else
    {
        error_log($message, 1,$contact_email);
        if (($e_number != E_NOTICE) && ($e_number < 2048))
        {
            echo '<p class="error">A system error occurred.  We apologize for the inconvenience.</p>';
        }
    }
}
set_error_handler('my_error_handler');

Note: I just typed this out, could be typos.

You will need to define the variables $debug (if true, prints the error message to the webpage), and contact email (if $debug is false, sends an email to this address about the error).


You would have to write your error handler to check the level of the error generated and decide whether or not to throw an exception based on that.

The second argument for set_error_handler lets you specify the error levels that the handler will be fired on. The first parameter to your handler is the error level number, so you can check that within the handler.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜