exception_handling -> not as robust as simply logging error?

ぃ、小莉子 提交于 2019-12-11 13:57:49

问题


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.


回答1:


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).




回答2:


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.



来源:https://stackoverflow.com/questions/5769537/exception-handling-not-as-robust-as-simply-logging-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!