我正在编写一个PHP web应用程序,它将在不久的将来在生产环境下运行,而不是使用非用户友好的die()
,我想我会提出一个Class
来处理ErrorMessages。
基本上,我的思维过程是这样的:
-
如果web应用程序处于调试/开发模式,die()是OK的
-
如果web应用程序处于生产/实时模式,不要用错误消息打扰用户-而是尽可能地继续,但发送电子邮件给管理员,转储错误消息和其他任何我们可以(例如:登录用户,会话详细信息,IP地址,时间等)
我的(大致)代码如下:
<?php
require_once('config.php');
class ErrorMessage
{
private $myErrorDescription;
public function __construct($myErrorDescription)
{
$this->myErrorDescription = (string) $myErrorDescription;
if (DEBUG_MODE === true)
die($myErrorDescription);
else
$this->sendEmailToAdministrator();
}
private function sendEmailToAdministrator()
{
// Send an e-mail to ERROR_LOGGING_EMAIL_ADDRESS with the description of the problem.
}
}
?>
此Class
将用作:
if (EXPECTED_OUTCOME) {
// ...
}
else {
new ErrorMessage('Application failed to do XYZ');
}
这是一个明智的方法,还是我在这里重新发明轮子?我知道框架通常有错误处理的解决方案,但我没有使用(也不想使用)。
也就是说,我应该使用Exceptions
和Throw
来代替吗?这种方法的优点和缺点是什么?
我建议使用exception。
你可以切换到发送异常而不是错误通过这样做:(从php ErrorException页)
<?php
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}
set_error_handler("exception_error_handler");
/* Trigger exception */
strpos();
?>
然后在代码中遇到错误条件时抛出异常
throw(new Exception("Meaningful Description", "optional error number"));
可以键入异常,这样您可以派生一个实例,以便您可以在catch
中将其作为目标。class MyRecoverableException extends Exception {}
然后在你的代码中,你可以将可能抛出潜在可恢复错误的代码包含在try/catch块中。
try {
$res = doSomething();
if (!$res) throw new MyRecoverableException("Do Somthing Failed");
} catch(MyRecoverableException $e){
logError($e);
showErrorMessage($e->getMessage());
}
这在数据库事务
中特别有用 try {
$db->beginTransaction();
// do a lot of selectes and inserts and stuff
$db->commit();
} catch (DBException $e){
$db->rollback();
logError($e);
showErrorMessage("I was unable to do the stuff you asked me too");
}
打开错误报告后,未捕获的异常将为您提供详细的堆栈跟踪,告诉您异常被抛出的位置。
关闭错误报告,你会得到一个500的错误。