我正在开发一个包含REST API组件的项目。我有一个专门用于处理所有REST API调用的控制器。
有没有办法捕获该特定控制器的所有异常,以便我可以对这些异常采取不同于其他应用程序控制器的操作?
IE:我想回复包含异常消息的XML / JSON格式的API响应,而不是默认的系统视图/堆栈跟踪(在API上下文中并不真正有用)。不希望不必在控制器中将每个方法调用包装在自己的try / catch中。
提前感谢您的任何建议。
答案 0 :(得分:37)
您可以通过注册 onError 和 onException 事件侦听器来完全绕过Yii的默认错误显示机制。
示例:
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;
}
// ...
}
答案 1 :(得分:9)
我无法在控制器中附加事件,我是通过重新定义CWebApplication类来完成的:
class WebApplication extends CWebApplication
{
protected function init()
{
parent::init();
Yii::app()->attachEventHandler('onError',array($this, 'handleApiError'));
Yii::app()->attachEventHandler('onException',array($this, 'handleApiError'));
}
/**
* Error handler
* @param CEvent $event
*/
public function handleApiError(CEvent $event)
{
$statusCode = 500;
if($event instanceof CExceptionEvent)
{
$statusCode = $event->exception->statusCode;
$body = array(
'code' => $event->exception->getCode(),
'message' => $event->exception->getMessage(),
'file' => YII_DEBUG ? $event->exception->getFile() : '*',
'line' => YII_DEBUG ? $event->exception->getLine() : '*'
);
}
else
{
$body = array(
'code' => $event->code,
'message' => $event->message,
'file' => YII_DEBUG ? $event->file : '*',
'line' => YII_DEBUG ? $event->line : '*'
);
}
$event->handled = true;
ApiHelper::instance()->sendResponse($statusCode, $body);
}
}
在index.php中:
require_once(dirname(__FILE__) . '/protected/components/WebApplication.php');
Yii::createApplication('WebApplication', $config)->run();
答案 2 :(得分:3)
您可以为每个控制器编写自己的actionError()函数。有几种方法可以解释here
答案 3 :(得分:1)
我正在使用以下基本控制器作为API,它不是无状态API,请注意,但它也可以提供服务。
类BaseJSONController扩展CController {
public $data = array();
public $layout;
public function filters()
{
return array('mainLoop');
}
/**
* it all starts here
* @param unknown_type $filterChain
*/
public function filterMainLoop($filterChain){
$this->data['Success'] = true;
$this->data['ReturnMessage'] = "";
$this->data['ReturnCode'] = 0;
try{
$filterChain->run();
}catch (Exception $e){
$this->data['Success'] = false;
$this->data['ReturnMessage'] = $e->getMessage();
$this->data['ReturnCode'] = $e->getCode();
}
echo json_encode($this->data);
}
}
您还可以捕获dbException并通过电子邮件发送这些内容,因为它们有点关键并且可以显示代码/数据库设计中的潜在问题。
答案 4 :(得分:0)
将此添加到您的控制器:
Yii::app()->setComponents(array(
'errorHandler'=>array(
'errorAction'=>'error/error'
)
));