我希望自己处理PHP应用程序中的异常。
当我抛出异常时,我希望传递一个标题以在错误页面中使用。
可以有人请提供一个好的教程链接或者清晰的解释异常处理如何工作(例如如何知道正在处理什么类型的异常等)。
官方文档是一个不错的入门指南-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();
}
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');