PHP自定义异常处理

11

我希望自己处理PHP应用程序中的异常。

当我抛出异常时,我希望传递一个标题以在错误页面中使用。

可以有人请提供一个好的教程链接或者清晰的解释异常处理如何工作(例如如何知道正在处理什么类型的异常等)。

3个回答

31

官方文档是一个不错的入门指南-http://php.net/manual/zh/language.exceptions.php.

如果你只是想捕获一条消息,你可以按照以下方式来做:

try{
    throw new Exception("This is your error message");
}catch(Exception $e){
    print $e->getMessage();
}

如果您想捕获特定的错误,可以使用以下方法:

try{
    throw new SQLException("SQL error message");
}catch(SQLException $e){
    print "SQL Error: ".$e->getMessage();
}catch(Exception $e){
    print "Error: ".$e->getMessage();
}

记录一下 - 你需要定义SQLException。可以简单地这样做:

class SQLException extends Exception{

}

对于标题和消息,您需要扩展Exception类:

class CustomException extends Exception{

    protected $title;

    public function __construct($title, $message, $code = 0, Exception $previous = null) {

        $this->title = $title;

        parent::__construct($message, $code, $previous);

    }

    public function getTitle(){
        return $this->title;
    }

}

您可以使用以下方式调用它:
try{
    throw new CustomException("My Title", "My error message");
}catch(CustomException $e){
    print $e->getTitle()."<br />".$e->getMessage();
}

1
谢谢,这个答案很棒。有了这个例子,如果我想传递一个标题以及除了消息之外的异常,我该怎么做呢? - Hailwood
5
W3Schools并非W3C所有,实际上是一个质量较差的资源,请参考http://w3fools.com了解更多信息。 - BoltClock
抱歉,我忘记了添加“学校”这个部分。不过我认为他们的异常处理指南已经是一个相当不错的入门了,但为了保持一致性,我会进行编辑并更换官方文档。 - Matt Lowden
@Haliwood - 我已经更新了回答你的问题。希望这可以帮到你。 - Matt Lowden
太棒了!正是我在寻找的 :) - Hailwood
1
@Matt 最好在 customException 类的 __construct 中定义一个公共消息和标题,如 $message = '...'。这样它将支持可重用性。 - Hashan

3
首先,我建议您查看对应的PHP手册页面,这是一个很好的开始。此外,您还可以查看扩展异常页面 - 这里有关于标准异常类的更多信息以及自定义异常实现的示例。
如果问题是如何在特定类型的异常被抛出时执行某些特定操作,则只需在catch语句中指定异常类型即可:
    try {
        //do some actions, which may throw exception
    } catch (MyException $e) {
        // Specific exception - do something with it
        // (access specific fields, if necessary)
    } catch (Exception $e) {
        // General exception - log exception details
        // and show user some general error message
    }

2

请将以下内容作为php页面的第一行。

它可以捕获php错误和异常。

function php_error($input, $msg = '', $file = '', $line = '', $context = '') {
    if (error_reporting() == 0) return;

    if (is_object($input)) {
        echo "<strong>PHP EXCEPTION: </strong>";
        h_print($input);
        $title  = 'PHP Exception';
        $error  = 'Exception';
        $code   = null;
    } else {
        if ($input == E_STRICT) return;
        if ($input != E_ERROR) return;
        $title  = 'PHP Error';
        $error  = $msg.' in <strong>'.$file.'</strong> on <strong>line '.$line.'</strong>.';
        $code   = null;
    }

    debug($title, $error, $code);

}

set_error_handler('php_error');
set_exception_handler('php_error');

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接