1
votes

I am using yii2 rest api module in which controller class extends an ActiveController and i have a problem dealing with the error exception . i need a proper json response when HTTP status code that are used by the Yii REST framework like 500 , 400. If i try a wrong method call on access api it show a exception object

object(yii\web\NotFoundHttpException)#170 (8) { ["statusCode"]=> int(404) 

In my config/main.php set the response

'response' => [
    'class' => 'yii\web\Response',
    'on beforeSend' => function ($event) {
        $response = $event->sender;
        if ($response->data !== null) {
           $response->data = [
             'success' => $response->isSuccessful,
             'data' => $response->data,
           ];
          $response->statusCode = 200;
        }
    },
]

It should display a msg like:

{
    "status": 0,
    "error_code": 400,
    "message": "Bad request"
}

I have try to add the behaviour verbs in controller using this link : click here

My whole application is based on api so please help me for handling all kind of errors

1

1 Answers

3
votes

Also depends on your server configs but usually you don't need any of that. this should be enough:

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

Here is an output example using those configs: https://yii2-f4a.rhcloud.com/api/tags