404 HTTP errors not being rendered in JSON using Zend framework 2

房东的猫 提交于 2019-12-10 16:04:36

问题


I'm creating a simple restful api using zend framework2 and I've references Rob Allen's notes on the subject as well as this excellent tutorial by http://hounddog.github.com/blog/getting-started-with-rest-and-zend-framework-2/

below is my module_config.php. You'll see that I have routes and the JSON view strategy configured. My understanding is that when you set up the JSON strategy in this fashion it accommodates all modules. The issue is that when an invalid route is entered the 404 response is sent back in html even though the Accept header is requesting Application/json.

I've been struggling with this for a 2 days now any advice or help would be appreciated

This curl call to the api generates the expected 404 error.

curl -i -H "Accept: application/json" http://myapi-dev.local/xxx/1

Module_config.php

return array(
    'controllers' => array(
        'invokables' => array(
            'Dips\Controller\Roles' => 'Dips\Controller\RolesController', //maps controller alias to a physical controller
        ),
    ),
    'router' => array(
        'routes' => array(
            'dips' => array(
                'type' => 'segment',
                'options' => array(
                  'route' => '/dips/roles/:apikey/:uname/:appname',
                  'constraints' => array(
                    'apikey' => '[a-zA-Z0-9]+',
                    'uname' => '[a-zA-Z]+',
                    'appname' => '[a-zA-Z][a-zA-Z0-9_-]*',
                 ),
                 'defaults' => array(
                     'controller' => 'Dips/Controller/Roles',
                  ),
                ),
            ),
        ),
    ),
    'view_manager' => array(
      'strategies' => array(
          'ViewJsonStrategy',
      ),
    ),
);

回答1:


You would need to implement an additional rendering strategy and put it in the stack above the default 404 rendering strategy. Alternatively, you could extend the existing ViewJsonStrategy to include error handling.

The default 404 Strategy is Zend/Mvc/View/Http/RouteNotFoundStrategy. If you look at it's detectNotFoundError method, you can see when it gets triggered.



来源:https://stackoverflow.com/questions/15252846/404-http-errors-not-being-rendered-in-json-using-zend-framework-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!