private function prepareErrorResponse(\Exception $ex)
    {
        ob_clean();

        $this->response = new Response();
        $this->response->setResponseCode(ResponseCode::HTTP_INTERNAL_SERVER_ERROR);

        $this->context->registerInstance($this->response);
        $this->context->registerInstance($ex);

        $rethrow = false;

        $this->filters->trigger(Filters::ON_EXCEPTION, $this->context);

        if (!$this->filters->anyHandlersForEvent(Filters::ON_EXCEPTION)) {
            // If this exception was completely unhandled, rethrow it so it appears as any old php exception
            $rethrow = true;
        }

        $this->finalizeOutputBuffer();

        if (empty($this->response->getBody())) {
            // If nothing was output, then at least present a default message to the user.
            $this->serveStaticPage('error_page');
        }

        if ($rethrow) {
            throw $ex;
        }
    }