PHP Zend自定义错误

本文介绍Zend框架中的ErrorController实现方式,包括如何针对不同类型的错误返回相应的HTTP状态码,并展示错误信息给用户。此外,还提供了在开发环境中显示详细错误信息的方法。

ErrorController.php

  1. <?php
  2. require_once 'Zend/Controller/Action.php';
  3. class ErrorController extends Zend_Controller_Action
  4. {
  5.     public function init()
  6.     {
  7.         $this->view->baseUrl = $this->_request->getBaseUrl();
  8.    }
  9.     public function errorAction()
  10.     {
  11.         
  12.         $errors = $this->_getParam('error_handler'); 
  13.         switch ($errors->type) { 
  14.             case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER: 
  15.             case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION: 
  16.                 // 404 error -- controller or action not found 
  17.                 $this->getResponse()->setHttpResponseCode(404); 
  18.                 $this->view->message = 'Page not found 404'
  19.                 break
  20.             default
  21.                 // application error 
  22.                 $this->getResponse()->setHttpResponseCode(500); 
  23.                 $this->view->message = 'Application error 500'
  24.                 break
  25.         } 
  26.         $this->view->env       = $this->getInvokeArg('env');
  27.         $this->view->exception = $errors->exception; 
  28.         $this->view->request   = $errors->request; 
  29.         
  30.     
  31.     }
  32. }

error.phtml

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  2. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd> 
  3. <html xmlns="http://www.w3.org/1999/xhtml"
  4. <head>  
  5.   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
  6.   <title>Zend Framework Quick Start</title> 
  7. </head> 
  8. <body> 
  9.   <h1>An error occurred</h1> 
  10.   <h2><?= $this->message ?></h2> 
  11.   <? if ('development' == $this->env): ?> 
  12.   <h3>Exception information:</h3> 
  13.   <p> 
  14.       <b>Message:</b> <?= $this->exception->getMessage() ?> 
  15.   </p> 
  16.   <h3>Stack trace:</h3> 
  17.   <pre> 
  18.   <?= $this->exception->getTraceAsString() ?> 
  19.   </pre> 
  20.   <h3>Request Parameters:</h3> 
  21.   <pre> 
  22.   <?= $this->request->getParams() ?> 
  23.   </pre> 
  24.   <? endif ?> 
  25. </body> 
  26. </html> 

以上代码来自Zend的官方QuickStart。

 

注意:使用自定义错误处理,不能在启动页面index.php中设置:

  1. $frontController->throwExceptions(true);

因为,如果设置了直接抛出错误,则不会进入ErrorController。

 

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值