Yii2 and handling exceptions

10,943

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);
Share:
10,943
Anton Abramov
Author by

Anton Abramov

Updated on June 18, 2022

Comments

  • Anton Abramov
    Anton Abramov almost 2 years

    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?