YII 2.0 REST API error handler

How to install a REST API error handler when the API is used as a module. I get an invalid 404 exception found in the HTML response and not the json / xml response.

this is an example api url with invalid entry point

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

here api is in the module and v1 in the api nested module.

answer

Not Found (# 404) The request "api / v1 / invalidentrypoint" failed. The above error occurred when the web server was processing your request. If you think this is a server error, please contact us. Thank.

I expect an answer like

** HTTP / 1.1 404 not found Date: Sun, March 02, 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; encoding = UTF-8 {"type": "yii \ web \ NotFoundHttpException", "name": "Not found exception", "message": "Requested resource not found.", "code": 0, "status": 404} **

Please, help.

+4
source share
1 answer

Have you tried setting the response format to json?

just add to the configuration:

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

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

Edit: using yii define from ethan comment the definition is "json", but this is a good estimate of using const const from Yii

+7
source

Source: https://habr.com/ru/post/1547531/


All Articles