Yii:捕获特定控制器的所有异常

编程入门 行业动态 更新时间:2024-10-13 00:32:43
本文介绍了Yii:捕获特定控制器的所有异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在处理一个包含 REST API 组件的项目.我有一个专门用于处理所有 REST API 调用的控制器.

有什么方法可以捕获该特定控制器的所有异常,以便我可以对这些异常采取与应用程序其他控制器不同的操作?

IE:我想用包含异常消息的 XML/JSON 格式的 API 响应来响应,而不是默认的系统视图/堆栈跟踪(这在 API 上下文中并没有真正有用).宁愿不必将控制器中的每个方法调用都包装在自己的 try/catch 中.

提前感谢您的任何建议.

解决方案

您可以通过注册 onErroronException 事件监听器来完全绕过 Yii 的默认错误显示机制.>

示例:

class ApiController 扩展了 CController{公共函数 init(){父::init();Yii::app()->attachEventHandler('onError',array($this,'handleError'));Yii::app()->attachEventHandler('onException',array($this,'handleError'));}公共函数handleError(CEvent $event){if ($event instanceof CExceptionEvent){//处理异常//...}elseif($event instanceof CErrorEvent){//处理错误//...}$event->handled = TRUE;}//...}

I am working on a project which includes a REST API component. I have a controller dedicated to handling all of the REST API calls.

Is there any way to catch all exceptions for that specific controller so that I can take a different action for those exceptions than the rest of the application's controllers?

IE: I'd like to respond with either an XML/JSON formatted API response that contains the exception message, rather than the default system view/stack trace (which isn't really useful in an API context). Would prefer not having to wrap every method call in the controller in its own try/catch.

Thanks for any advice in advance.

解决方案

You can completely bypass Yii's default error displaying mechanism by registering onError and onException event listeners.

Example:

class ApiController extends CController
{
  public function init()
  {
    parent::init();

    Yii::app()->attachEventHandler('onError',array($this,'handleError'));
    Yii::app()->attachEventHandler('onException',array($this,'handleError'));
  }

  public function handleError(CEvent $event)
  {        
    if ($event instanceof CExceptionEvent)
    {
      // handle exception
      // ...
    }
    elseif($event instanceof CErrorEvent)
    {
      // handle error
      // ...
    }

    $event->handled = TRUE;
  }

  // ...
}

这篇关于Yii:捕获特定控制器的所有异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-23 19:15:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1047431.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:控制器   异常   Yii

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!