Anton Abramov
Anton Abramov

Reputation: 2331

Yii2 and handling exceptions

I'm building REST APi for my app, based on Yii2. So, i have a problem with dealing exceptions. For example i need to throw 405 HTTP code when someone use wrong HTTP verb, but i wanna send back something like this:

{meta:{error:{code:405,message:"Wrong method"}}}

So, i need to catch Exception's and modify Response object. But how can i do this? In Yii there were onError and onException events. What about Yii2?

Upvotes: 6

Views: 11207

Answers (1)

Sergey Onishchenko
Sergey Onishchenko

Reputation: 7851

First you need to specify the needed response format in the components section of the config:

    'response' => [
        'format' => yii\web\Response::FORMAT_JSON,
        'charset' => 'UTF-8'
    ]

Then just do something like this:

throw new \yii\web\HttpException(400, 'Wrong method', 405);

Upvotes: 5

Related Questions