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:
- I'd like the 404 route for some endpoints
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?
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:
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: