PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, March 3, 2022

[FIXED] YII 2.0 REST API error handler

 March 03, 2022     php, yii, yii2     No comments   

Issue

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.


Solution

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



Answered By - Jeffom
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing