【发布时间】:2011-11-21 15:07:51
【问题描述】:
如果发生在 php 网页上,我想记录错误并将用户重定向到自定义错误页面。这怎么可能实现。我目前正在使用
set_error_handler('my_error_handler');
用于记录所有错误。
在php中处理错误后显示错误页面的最佳做法是什么。
【问题讨论】:
标签: php exception-handling error-handling
如果发生在 php 网页上,我想记录错误并将用户重定向到自定义错误页面。这怎么可能实现。我目前正在使用
set_error_handler('my_error_handler');
用于记录所有错误。
在php中处理错误后显示错误页面的最佳做法是什么。
【问题讨论】:
标签: php exception-handling error-handling
我为此编写了一个自定义类:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
class CommonException extends Exception {
private $logFile = "../log/commonEx.log";
private $log = Array();
public $code = "";
public function __construct($message = null, $code = 0) {
$exLog['msg'] = $message;
$exLog['code'] = $code;
$this->code = $code;
$exLog['file'] = $this->getFile();
$exLog['line'] = $this->getLine();
$this->log = $exLog;
$this->_writeToLog($exLog);
sfLoader::loadHelpers('I18N');
}
public function display() {
return $this->log;
}
private function _writeToLog($exLog) {
error_log(implode("|", $exLog) . "\r\n", 3, $this->logFile);
}
}
在您的try .. catch 块中:
try {
// ...
} catch (Exception $e) {
$errMsg = new CommonException($e->getMessage(), $e->getCode());
// redirect to anywhere you want
}
【讨论】:
永远不应使用重定向。
只需在适当的位置显示错误页面。只需在错误处理程序中添加这些行
header("HTTP/1.1 503 Service Unavailable");
readfile($_SERVER['DOCUMENT_ROOT']."/503.html");
exit;
当然,只有使用模板正确规划您的应用程序,在所有逻辑完成之前不进行任何输出时,它才会起作用
【讨论】:
如果您愿意,可以使用 PHP Exceptions。它们不太受欢迎(目前,无论如何),但它们工作得很好。
只需throw new MyException("Error text") 并在主页面执行期间捕获它,您可以在其中打印漂亮的错误页面。
【讨论】: