在 AfterAction 中记录数据库异常? Yii2 框架

Logging Exceptions to Database In AfterAction? Yii2 Framework

我有一个扩展 yii\rest\ActiveController 的控制器。我已经覆盖了 beforeAction() 方法以将部分请求记录到数据库(我将此 id 存储在控制器的私有变量中)。然后在 afterAction() 方法中 - 我用响应代码 + 结果更新适当的日志 ID。

如果我有一个 2xx 错误,这一切都可以正常工作,但是一旦我进入 400 秒、500 秒,我认为这不起作用,因为 afterAction 永远不会触发。

是否有我可以覆盖的特定函数以在控制器级别捕获异常并记录错误?

解决方案是将以下方法添加到我的控制器中:

 use yii\web\Response;
 use yii\web\ResponseEvent;

并处理 beforeSend 事件

  public function init(){
                    parent::init();

                    //before we send the client the response, do work
                    Yii::$app->response->on(Response::EVENT_BEFORE_SEND,function($event){
                    $response = $event->sender;
                    //$response will have $response->statusCode etc so you can log the result here

                    });
                }