protected function _outputMessage($template)
    {
        if (!$this->controller->request->accepts('application/vnd.api+json')) {
            return parent::_outputMessage($template);
        }

        $viewVars = $this->controller->viewVars;
        $code = $this->controller->response->getStatusCode(); // e.g. 404
        $title = $this->controller->response->getReasonPhrase(); // e,g. Not Found

        // Only set JSON API `detail` field if `message` viewVar field is not
        // identical to the CakePHP HTTP Status Code description.
        $detail = null;
        if (!empty($viewVars['message']) && (strcasecmp($viewVars['message'], $title) !== 0)) {
            $detail = $viewVars['message'];
        }

        $errorCollection = new ErrorCollection();
        $errorCollection->add(new Error(
            $idx = null,
            $aboutLink = null,
            $status = null,
            $code,
            $title,
            $detail,
            $source = null,
            $meta = null
        ));

        $encoder = Encoder::instance();
        $json = $encoder->encodeErrors($errorCollection);

        if (Configure::read('debug')) {
            $json = $this->_addDebugNode($json);
            $json = $this->_addQueryLogsNode($json);
        }

        # create stream as required by `response->withBody()`
        $stream = new Stream('php://memory', 'wb+');
        $stream->write($json);

        // set up the response
        $this->controller->response = $this->controller->response
            ->withType('jsonapi')
            ->withBody($stream);

        return $this->controller->response;
    }