How to add additional Property in Response triggered through BadRequestHttpException()

Hi Experts,

When throwing BadRequestHttpException() in Yii2 Response has following fields
{
“name”: “Bad Request”,
“message”: “The Refresh Token is invalid”,
“code”: 0,
“status”: 400,
“type”: “yii\web\BadRequestHttpException”
}
This is OK. However we are integrating our system with one of Google Assistant Service and in case of invalid refresh token the expect “error” property with “Invalid_grant” in 400 response. I am struggling for last 3 days but unable to add additional property in Http response. I need to send response like below
{
“name”: “Bad Request”,
“error”: “invalid_grant”,
“message”: “The Refresh Token is invalid”,
“code”: 0,
“status”: 400,
“type”: “yii\web\BadRequestHttpException”
}

Tried multiple ways but not able to add additional filed “error” in the response. As a result automated test suite set by Google is failing for invalid refresh token (google documentation). Can you please guide me how to add additional filed.

Hi.
As long as the Response extends Component you can manipulate its content for example by attaching to the Response’s EVENT_AFTER_PREPARE event.

In a hurry so maybe bit ugly but works. In action:

Yii::$app->response->on(Response::EVENT_AFTER_PREPARE, function($event){
        $event->sender->data = array_merge ($event->sender->data, $event->data);
        $event->sender->formatters['json']->format($event->sender);
    }, ['error' => 'Invalid_grant']
    );
    // Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    throw new BadRequestHttpException('The Refresh Token is invalid');