时间:2021-07-01 10:21:17 帮助过:2人阅读
在发生错误时,将用户重定向到另一个页面。
1 php 2 header('content-type:text/html; charset=utf-8'); 3 4 class ExceptionRedirectHandler{ 5 6 protected $_exception; 7 protected $redirect = '404.html'; 8 protected $_logFile = 'D:/practise/php/Error/LogException3.log'; 9 10 //构造函数中得到异常对象11 public function __construct(Exception $e){12 $this->_exception = $e;13 }14 15 public static function handle(Exception $e){16 $self = new self($e);17 $self->log();18 //清除所有的输出缓冲19 while(@ob_end_clean());20 header('HTTP/1.1 307 Temporary Rediret');21 header('Cache-Control:no-cache, must-revalidate');22 header('Expires: Sun, 05 Jul 2015 22:36:42 GMT');23 header('Location:'.$self->redirect);24 exit(1);25 }26 27 public function log(){28 error_log($this->_exception->getMessage().PHP_EOL, 3, $this->_logFile);29 }30 }31 32 set_exception_handler(array('ExceptionRedirectHandler', 'handle'));33 34 //测试35 $conn = mysql_connect('localhost', 'root', 'root123');36 if(!$conn){37 throw new Exception("数据库连接失败");38 39 }
跳转到 404 页面: