Ignoring the default 404 route in ZF3 MVC

882 Views Asked by At

Currently, for my GET endpoints in RESTFUL Zend Framework 3, if I can't find the item the user requests through the paramaters I send 400 with JSON API errors like so:

$this->response->setStatusCode(Response::STATUS_CODE_400);
return JsonModel([
    'errors' => [
        [ 'title' => 'Not found' ]
    ]
]);

The correct status of course is 404. However as soon as I set $this->response->setStatusCode(Response::STATUS_CODE_404); the default 404 route is displayed. How do I disable it?

I tried commenting out the following in module.config.php

. . .
'view_manager' => [
    // 'display_not_found_reason' => true,
    'display_exceptions'       => true,
    'doctype'                  => 'HTML5',
    // 'not_found_template'       => 'error/404',
    'exception_template'       => 'error/index',
    'strategies' => [
        'ViewJsonStrategy',
    ],
    . . .
],

That works, except I have two problems:

  1. I'd like the 404 route for some endpoints
  2. It adds information to the return JSON I don't want sent

    { "errors": [ { "title": "Not Found", } ], "message": "Page not found.", "display_exceptions": true, "controller": "Company\Module\Controller\RestfulController", "controller_class": null }

What are my options?

1

There are 1 best solutions below

0
Jannes Botis On

Your issue is caused by Zend\Mvc\View\Http\RouteNotFoundStrategy, which is registered by your default view manager. You can see that at Zend\Mvc\View\Http\ViewManager:

$routeNotFoundStrategy   = $services->get('HttpRouteNotFoundStrategy');

Even if you use 'display_exceptions' => false, message is still appended.

To overcome this, one solution is to inject the model content to the response and return the latter directly on your view:

$this->response->setStatusCode(Response::STATUS_CODE_404);
$model = new JsonModel([
        'errors' => [
            [ 'title' => 'Not found' ]
        ]
]);
return $this->getResponse()->setContent($model->serialize());