Error handling
Sometimes you may want to customize the default error response format. For example, we need to know the response timestamp and whether the response is successful. Frameworks provide an easy way to do this.
Getting ready
Repeat all the steps from the Creating a REST server recipe's in the Getting ready and How to do it… sections.
How to do it…
To achieve this goal, you can respond to the beforeSend
event of the response component in @app/config/web.php,
as follows:
'response' => [ 'class' => 'yii\web\Response', 'on beforeSend' => function ($event) { $response = $event->sender; if ($response->data !== null) { $response->data = [ 'success' => $response->isSuccessful, 'timestamp' => time(), 'path' => Yii::$app->request->getPathInfo(), 'data' => $response->data, ]; } }, ],
How it works…
To learn what happens in this code, let's play a bit...