PHP中的错误处理并重定向到错误页面

时间:2011-09-21 05:07:53

标签: php exception-handling error-handling

我想在php网页上发生错误,并将用户重定向到自定义错误页面。如何实现这一目标。我目前正在使用

set_error_handler('my_error_handler');

用于记录所有错误。

在php中处理错误后显示错误页面的最佳做法是什么。

3 个答案:

答案 0 :(得分:0)

如果您愿意,可以使用PHP Exceptions。它们并不太受欢迎(目前,无论如何),但它们只是起作用。

只需throw new MyException("Error text")并在主页执行期间抓住它,您可以在其中打印漂亮的错误页面。

答案 1 :(得分:0)

永远不要使用重定向 只需显示错误页面。只需在错误处理程序中添加这些行

即可
header("HTTP/1.1 503 Service Unavailable");
readfile($_SERVER['DOCUMENT_ROOT']."/503.html");
exit;

当然,只有使用模板正确规划应用程序,在所有逻辑完成之前不进行输出,它才会起作用

答案 2 :(得分:0)

i wrote custome class for this 

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 any where you want
        }