Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 and handling exceptions

Tags:

rest

http

php

yii2

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?

like image 992
Anton Abramov Avatar asked May 11 '14 04:05

Anton Abramov


1 Answers

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);
like image 79
Sergey Onishchenko Avatar answered Nov 13 '22 07:11

Sergey Onishchenko