protected function encodeException($exception, ResponseInterface $response, $status = 500)
    {
        $error = ['message' => $exception->getMessage(), 'type' => get_class($exception)];

        if ($this->getDisplayErrorDetails()) {
            $error['exception'] = [];

            do {
                $error['exception'][] = [
                    'type' => get_class($exception),
                    'code' => $exception->getCode(),
                    'message' => $exception->getMessage(),
                    'file' => $exception->getFile(),
                    'line' => $exception->getLine(),
                    'trace' => explode("\n", $exception->getTraceAsString()),
                ];
            } while ($exception = $exception->getPrevious());
        }

        return $response->write(json_encode($error))->withStatus($status);
    }