我想自己处理我的php应用程序中的异常.
当我抛出异常时,我想传递一个标题,以便在错误页面中使用.
有人可以把我链接到一个好的教程,或者写一个关于异常处理实际如何工作的明确解释(例如,如何知道你正在处理的异常类型等.
Mat*_*den 29
官方文档是一个很好的起点 - http://php.net/manual/en/language.exceptions.php.
如果它只是您要捕获的消息,则可以按照以下方式执行此操作;
try{
throw new Exception("This is your error message");
}catch(Exception $e){
print $e->getMessage();
}
Run Code Online (Sandbox Code Playgroud)
如果您想捕获您将使用的特定错误:
try{
throw new SQLException("SQL error message");
}catch(SQLException $e){
print "SQL Error: ".$e->getMessage();
}catch(Exception $e){
print "Error: ".$e->getMessage();
}
Run Code Online (Sandbox Code Playgroud)
为了记录 - 你需要定义SQLException.这可以简单地完成:
class SQLException extends Exception{
}
Run Code Online (Sandbox Code Playgroud)
对于标题和消息,您可以扩展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;
}
}
Run Code Online (Sandbox Code Playgroud)
你可以使用以下方法调用它:
try{
throw new CustomException("My Title", "My error message");
}catch(CustomException $e){
print $e->getTitle()."<br />".$e->getMessage();
}
Run Code Online (Sandbox Code Playgroud)