【发布时间】:2011-06-11 15:11:04
【问题描述】:
我想自己处理我的 PHP 应用程序中的异常。
当我抛出异常时,我想传递一个标题以在错误页面中使用。
有人可以将我链接到一个好的教程,或者写一个关于异常处理实际工作原理的清晰解释(例如,如何知道你正在处理什么样的异常等。
【问题讨论】:
我想自己处理我的 PHP 应用程序中的异常。
当我抛出异常时,我想传递一个标题以在错误页面中使用。
有人可以将我链接到一个好的教程,或者写一个关于异常处理实际工作原理的清晰解释(例如,如何知道你正在处理什么样的异常等。
【问题讨论】:
官方文档是一个很好的起点 - http://php.net/manual/en/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();
}
【讨论】:
首先,我建议您查看corresponding PHP manual page,这是一个很好的起点。此外,您可以查看Extending Exceptions 页面 - 有一些关于标准异常类的更多信息,以及自定义异常实现的示例。
如果问题是,如果抛出了特定类型的异常,如何做一些特定的操作,那么你只需要在 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
}
【讨论】:
将此作为您的 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');
【讨论】: