Bogdan
Bogdan

Reputation: 2042

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?

Upvotes: 1

Views: 1203

Answers (2)

Yagnik Devani
Yagnik Devani

Reputation: 1

**you need to send httpException **

throw new \yii\web\HttpException(404, 'The requested Item could not be found.');

Upvotes: 0

Ebrahim Poursadeqi
Ebrahim Poursadeqi

Reputation: 1816

you can send your reason like this

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

Upvotes: 3

Related Questions