Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

YII 2.0 REST API error handler

Tags:

php

yii

yii2

How to set a REST API error handler, when API used as a module. I'm getting an invalid 404 found exception in HTML response rather than a json/xml response.

this is the sample api URL with an invalid entry point

http://localhost.backend.com/api/v1/invalidentrypoint

here api is in a module and v1 in nested with api module.

the reponse is

Not Found (#404) Unable to resolve the request "api/v1/invalidentrypoint". The above error occurred while the Web server was processing your request. Please contact us if you think this is a server error. Thank you.

I'm expecting a response like

**HTTP/1.1 404 Not Found Date: Sun, 02 Mar 2014 05:31:43 GMT Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y Transfer-Encoding: chunked

Content-Type: application/json; charset=UTF-8 { "type": "yii\web\NotFoundHttpException", "name": "Not Found Exception", "message": "The requested resource was not found.", "code": 0, "status": 404 }**

please help.

like image 654
user2959221 Avatar asked Jul 08 '14 05:07

user2959221


1 Answers

Have you tried setting the response format to json?

just add to the config:

'response' => [
    'format' =>  \yii\web\Response::FORMAT_JSON
]

here's some info from the yii documentation: https://github.com/yiisoft/yii2/blob/master/docs/guide/rest-error-handling.md

Edit: using the yii define from ethan's comment the define is "json" but it's a good pratice to use the defined const from Yii

like image 54
Jeffom Avatar answered Sep 20 '22 16:09

Jeffom