【发布时间】:2013-11-20 20:52:17
【问题描述】:
我试图更好地理解异常处理。我有一个自定义错误处理程序。在没有邮件服务器的情况下运行以下函数时,它会正确触发错误处理程序并返回“Tough Luck”。在错误处理程序中,我必须throw new ErrorException() 才能激活try/catch。没有这条语句,出错后程序会继续执行下一行代码(在本例中返回“Feedback left”)。
能够继续下一行代码很有用,因为用户不会收到刺耳的错误消息和警告。但是,我希望能够在选定的情况下使用 Try/Catch。
有什么更好的方法来处理用户看不到但我可以使用 try/catch 的错误?有没有办法抛出新的 ErrorException(使用 $e->getSeverity()?),如果存在 try/catch,则会处理它,但如果没有,则忽略异常?
set_error_handler('exceptions_error_handler');
error_reporting(E_ALL ^ E_STRICT);
echo feedback();
function feedback(){
try{
mail("m@localhost","subject","body","From: me");
return "Feedback left.";
}
catch(Exception $e){
error_log("Error sending feedback email." . "Some Custom Info For Error Log");
return "Tough Luck";
}
}
function exceptions_error_handler( $errno, $errmsg, $errfile, $errline, $context = null ){
// custom log file handling
log_exception( new ErrorException( $errmsg, 0, $errno, $errfile, $errline) );
// required in order for the try/catch to be activated
throw new ErrorException($errmsg, 0, $errno, $errfile, $errline);
}
【问题讨论】:
标签: php error-handling try-catch