I have a controller that extends yii\rest\ActiveController. I have overriden the beforeAction() method to log part of the request to the database (I store this id in a private variable in the controller). Then in the afterAction() method - I update the appropriate log id with response code + result.
This all works fine if I have a 2xx error, but once I get into 400s, 500s, that have been thrown this does not work I would assume because afterAction never fires.
Is there a particular function I can override to catch the exception at a controller level and log the error?
The solution was to add the following method to my Controller:
use yii\web\Response;
use yii\web\ResponseEvent;
and handle the beforeSend event
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
});
}