Customise error controller

I want to customize the error exception and give back the response in JSON format. Please look at this link “” what I want to do.

I’m receiving an API exception response in HTML format but I want in Json format. I don’t know how to customize it. Any help is highly appreciable.

I’ve never used these tools but…

Have you looked at this section of the book? In particular this option:

exceptionRenderer - string - The class responsible for rendering uncaught exceptions. If you choose a custom class you should place the file for that class in src/Error . This class needs to implement a render() method.

seems like it would apply to your problem.

1 Like

As @dreamingmind said you should create your custom exceptionRenderer.
See this file example, you can also overwrite the render method.

Make sure to only overwrite response if the request is api, otherwise return default render() method, like:

namespace App\Error;

// use statements

class ApiExceptionRenderer extends ExceptionRenderer
     * Renders the response for the exception.
     * @return \Cake\Http\Response The response to be sent.
    public function render()
        if (! $this->request->is('api')) {
            return parent::render();

        // your logic to return json response goes here

You should add detector when you are in your api class using, so it will be available in your custom exceptionRenderer class:

$this->getRequest()->addDetector('api', function () {
    return true;

This will pretty much do it, still if you have any problem just let us know.