Skip to content
Advertisement

Set reason for thrown bad request in Yii 2

I’m writing an API and I have to throw HTTP 400 bad request like below

if (!$model->validate()) {
    throw new BadRequestHttpException;
}

and it works fine meaning that it displays the default HTTP 400 page (I have no views defined because I’m building an API)

What I would like to achieve is to give some reason for the bad request error thrown so that who is using the API knows why his request is bad.

Tried the following but with no success

if (!$model->validate()) {
    Yii::$app->response->content = 'This is the reason for your bad request';
    throw new BadRequestHttpException;
}

any ideas?

Advertisement

Answer

you can send your reason like this

if (!$model->validate()) {
    throw new BadRequestHttpException('This is the reason for your bad request');
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement