cakephp 3 rest errors return as html CrudJsonApi


cakephp 3 rest errors return as html CrudJsonApi



I'm adding a REST API onto an existing cakephp codebase.



It is working as I expect. I hit /api/v1/contacts/12312 and get json data back for contact 12312. If put an id of a contact that doesn't exist then I get the html 404 page error rather than json.



This happens internally on the contacts->get($id) line.



In the api app controller I have


public function initialize()
{

parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Crud.Crud', [
'actions' => [
'Crud.Index',
'Crud.View',
'Crud.Add',
'Crud.Edit',
'Crud.Delete'
],
'listeners' => [
'CrudJsonApi.JsonApi',
'CrudJsonApi.Pagination', // Pagination != ApiPagination
'Crud.ApiQueryLog',


],
'Error' => [
'errorLevel' => E_ALL,
'exceptionRenderer' => 'CrudJsonApiErrorJsonApiExceptionRenderer',
'skipLog' => ,
'log' => true,
'trace' => true,
],
]);



$this->Crud->config(['listeners.jsonApi.exceptionRenderer' => 'CrudJsonApiErrorJsonApiExceptionRenderer']);

$this->setJsonResponse();
}



public function beforeRender(Event $event)
{
$this->RequestHandler->renderAs($this, 'json');
$this->response->type('application/json');
$this->set('_serialize', true);
}



I thought using the JsonApiExceptionRenderer 404 errors would be handled with json output.



Also the Pagination works but the Pagination data isnt returned with the response...


{
"viewVar": "crmContacts",
"crmContacts": [
{
"id": 1,
"lastname": "testname1"
},
{
"id": 2,
"lastname": "smith"
}
],
"success": true
}



Any ideas?



Thanks





Did you wrap the command with try/catch?
– Franz
Jul 2 at 15:54





You should use "find" instead of "get" if you don't want to handle an exception when the record doesn't exist
– Franz
Jul 2 at 15:56





I am not familiar with the Crud JSON API plugin (please always mention the software that you are using!), but according to the docs, you're not configuring things correctly, the JsonApiExceptionRenderer is ment to be set in the application configuration, not the Crud component configuration. github.com/FriendsOfCake/crud-json-api/blob/0.4.0/docs/preface/…
– ndm
Jul 2 at 21:26


JsonApiExceptionRenderer


Crud





I have solved this now. It shouldn't of had the beforerender code. Thanks
– Jim Phillips
Jul 3 at 7:41









By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.