1

我编写了以下自定义异常处理程序:

namespace System\Exception;

class Handler extends \Exception {


    public static function getException($e = null) {

        if (ENVIRONMENT === 0 && is_object($e)) {       
            $message  = "<p>";
            $message .= "Exception: " . $e->getMessage();
            $message .= "<br />File: " . $e->getFile();
            $message .= "<br />Line: " . $e->getLine();
            $message .= "<br />Trace: " . $e->getTrace();
            $message .= "<br />Trace as string: " . $e->getTraceAsString();
            $message .= "</p>";
        } else {
            $message  = '<h1>Exception</h1>';
            $message .= '<p>There was a problem.</p>';
        }

        @require_once('header.php');
        echo $message;
        @require_once('footer.php');

        exit();

    }


    public static function getError($errno = 0, $errstr = null, $errfile = null, $errline = 0) {
        if (ENVIRONMENT === 0) {        
            $message  = "<p>";
            $message .= "Error: " . $errstr;
            $message .= "<br />File: " . $errfile;
            $message .= "<br />Line: " . $errline;
            $message .= "<br />Number: " . $errno;
            $message .= "</p>";
        } else {
            $message  = '<h1>Error</h1>';
            $message .= '<p>There was a problem.</p>';
        }

        @require_once('header.php');
        echo $message;
        @require_once('footer.php');

        exit();

    }   


    public static function getShutdown() {
        $last_error = error_get_last();
        if ($last_error['type'] === E_ERROR) {
            self::getError(E_ERROR, $last_error['message'], $last_error['file'], $last_error['line']);
        }
    }


}

并表示我想使用这个类及其方法来处理系统产生的所有异常和错误,方法如下:

set_exception_handler(array("System\Exception\Handler", "getException"));
set_error_handler(array("System\Exception\Handler", "getError"), -1 & ~E_NOTICE & ~E_USER_NOTICE);
register_shutdown_function(array("System\Exception\Handler", "getShutdown"));

我还表示我不希望在屏幕上显示错误并报告所有错误:

ini_set('display_errors', 'Off');
error_reporting(-1);

我现在的问题是 - 我还需要使用 try { } catch () { } 语句来捕获任何异常和错误吗?我知道以上内容很可能不是防弹的,但到目前为止似乎没有任何 try / catch 语句通过处理所有未捕获的异常和错误来工作。

另外 - 使用自定义异常处理程序并让它捕获所有未捕获的异常而不是通过 try {} catch (即性能/安全等)这样做有什么缺点吗?

4

2 回答 2

3

您不必这样做,但您无法恢复 - 使用 try/catch 具有对特定异常做出反应的优势(例如,在 some_custom_session_handling() 中找不到文件可能是使用 try/catch 并注销此类用户的好地方没有会话文件)。

所以好处是你有更漂亮的消息。缺点是您总是以相同的方式对待异常。它本身还不错,不应该降低性能或安全性,但它首先忽略了使用异常的要点。

但是,它不排除在您可能需要的地方使用 try/catch,所以我会说这是一个很好的故障转移解决方案,但应该避免作为 try/catch 的替代品

于 2012-08-03T16:49:10.087 回答
0

正如jderda所说,使用你的方法你错过了异常点:检查代码上层的任何错误并对它们做出反应 - 停止或处理异常并继续前进。例如,当您想要记录所有未捕获的异常时,您的方法很好

于 2012-08-03T16:56:22.483 回答