Yii:捕获特定控制器的所有异常 [英] Yii: Catching all exceptions for a specific controller
问题描述
我正在处理一个包含 REST API 组件的项目.我有一个专门用于处理所有 REST API 调用的控制器.
有什么方法可以捕获该特定控制器的所有异常,以便我可以对这些异常采取与应用程序其他控制器不同的操作?
IE:我想用包含异常消息的 XML/JSON 格式的 API 响应来响应,而不是默认的系统视图/堆栈跟踪(这在 API 上下文中并没有真正有用).宁愿不必将控制器中的每个方法调用都包装在自己的 try/catch 中.
提前感谢您的任何建议.
您可以通过注册 onError 和 onException 事件监听器来完全绕过 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屋!