[英]php custom exception handling
我想自己在我的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();
}
首先,我建议您查看相应的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
}
尝试这是你的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');
你可以浏览php.net和w3学校的基础知识,也可以试试这个链接:
http://ralphschindler.com/2010/09/15/exception-best-practices-in-php-5-3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.