If the request failed, then check if a cached response would suffice.

@param ErrorEvent $event
497201
public function onError(ErrorEvent $event)
    {
        $request = $event->getRequest();

        if (!call_user_func($this->canCache, $request)) {
            return;
        }

        $response = $this->storage->fetch($request);

        // Intercept the failed response if possible
        if ($response && $this->validateFailed($request, $response)) {
            $request->getConfig()->set('cache_hit', 'error');
            $response->setHeader('Age', Utils::getResponseAge($response));
            $event->intercept($response);
        }
    }
31123
public function onRequestException(Event $event)
    {
        if (!$event['exception'] instanceof CurlException) {
            return;
        }

        $request = $event['request'];
        if (!$this->canCache->canCacheRequest($request)) {
            return;
        }

        if ($response = $this->storage->fetch($request)) {
            $response->setHeader('Age', time() - strtotime($response->getDate() ? : 'now'));
            if (!$this->canResponseSatisfyFailedRequest($request, $response)) {
                return;
            }
            $request->getParams()->set('cache.hit', 'error');
            $request->setResponse($response);
            $this->addResponseHeaders($request, $response);
            $event->stopPropagation();
        }
    }
1169000
public function onKernelRequest(RestEvent $event)
    {
        $request = $event->getRequest();

        if ($request->headers->has('Accept')) {

            $format = $request->getFormat($request->headers->get('Accept'));

            if (!empty($format)) {
                $request->setRequestFormat($format);
            }
        }
    }
242439
public function handleRequest(GetResponseEvent $event)
    {
        if (!($tagcacheConfig = $this->getTagcacheConfig($event->getRequest()))) {
            return;
        }

        if (is_array($cacheContent = $this->tagcache->get($tagcacheConfig->getKey()))) {
            if ($cacheContent['Expires'] - (time() - $cacheContent['CreatedAt']) < 0) {
                return;
            }
            $response = new TagcacheResponse($this->renderCacheContent($cacheContent));
            $response->headers->add($cacheContent['Headers']);
            $event->setResponse($response);
        }
    }
1292842
public function handleEventScriptEvent($event)
    {
        \Cache::forget(Cache::EVENT_SCRIPT_CACHE_PREFIX . $event->script->name);

        return true;
    }
241630
protected function handleError(Event $event): void
    {
        $logErrors = $this->configuration
            ->get('log_errors')
        ;
        $emailErrors = $this->configuration
            ->get('email_errors')
        ;

        if ($logErrors) {
            $this->logger->error($this->formatEventError($event));
        } else {
            $output = $event->wholeOutput();

            $this->output
                ->write("<error>{$output}</error>");
        }

        // Send error as email as configured
        if ($emailErrors) {
            $this->mailer->send(
                'Crunz: reporting error for event:' . (($event->description) ? $event->description : $event->getId()),
                $this->formatEventError($event)
            );
        }
    }
821030
public function onKernelException(GetResponseForExceptionEvent $event)
    {
        $request = $event->getRequest();
        $exception = $event->getException();
        if (!$exception instanceof HttpExceptionInterface || Zone::isBackend($request)) {
            return;
        }
        if ($exception->getStatusCode() !== Response::HTTP_NOT_FOUND) {
            return;
        }
        // If no zone is set, assume front-end as SELECT queries can leak unpublished records
        if (Zone::get($request) === null) {
            Zone::set($request, Zone::FRONTEND);
        }

        foreach ($this->notFoundPage as $item) {
            try {
                $this->renderNotFound($event, $item);

                return;
            } catch (LoaderError $e) {
                // Template not found, fall though to see if we can render a
                // record, failing that let the exception handler take over
            }

            $content = $this->storage->getContent($item, ['returnsingle' => true]);
            if ($content instanceof Content && !empty($content->id)) {
                $template = $this->templateChooser->record($content);
                $this->renderNotFound($event, $template, $content->getTemplateContext());

                return;
            }
        }

        $msg = sprintf(
            'No page could be shown, because the "notfound" setting "%s" in config.yml or theme.yml is not valid.',
            implode(', ', $this->notFoundPage)
        );
        $event->setException(new NotFoundHttpException($msg, $e));
    }
226318
public function onRequestSent(Event $event)
    {
        $response = $event['response'];
        $request = $event['request'];

        // Only act on redirect requests with Location headers
        if (!$response || $request->getParams()->get(self::DISABLE)) {
            return;
        }

        // Trace the original request based on parameter history
        $original = $this->getOriginalRequest($request);

        // Terminating condition to set the effective repsonse on the original request
        if (!$response->isRedirect() || !$response->hasHeader('Location')) {
            if ($request !== $original) {
                // This is a terminating redirect response, so set it on the original request
                $response->getParams()->set(self::REDIRECT_COUNT, $original->getParams()->get(self::REDIRECT_COUNT));
                $original->setResponse($response);
                $response->setEffectiveUrl($request->getUrl());
            }
            return;
        }

        $this->sendRedirectRequest($original, $request, $response);
    }
1075275
public function onBefore(BeforeEvent $event)
    {
        $request = $event->getRequest();

        if (!$this->canCacheRequest($request)) {
            $this->cacheMiss($request);
            return;
        }

        if (!($response = $this->storage->fetch($request))) {
            $this->cacheMiss($request);
            return;
        }

        $response->setHeader('Age', Utils::getResponseAge($response));
        $valid = $this->validate($request, $response);

        // Validate that the response satisfies the request
        if ($valid) {
            $request->getConfig()->set('cache_lookup', 'HIT');
            $request->getConfig()->set('cache_hit', true);
            $event->intercept($response);
        } else {
            $this->cacheMiss($request);
        }
    }
478041
public function beforeRender(Event $event)
    {
        $this->httpStatusCode = $this->response->getStatusCode();

        $messageArr = $this->response->withStatus($this->httpStatusCode);

        if (Configure::read('ApiRequest.debug') && isset($this->viewVars['error'])) {
            $this->apiResponse[$this->responseFormat['messageKey']] = $this->viewVars['error']->getMessage();
        } else {
            $this->apiResponse[$this->responseFormat['messageKey']] = !empty($messageArr[$this->httpStatusCode]) ? $messageArr[$this->httpStatusCode] : 'Unknown error!';
        }

        Configure::write('apiExceptionMessage', isset($this->viewVars['error']) ? $this->viewVars['error']->getMessage() : null);

        parent::beforeRender($event);

        $this->viewBuilder()->setClassName('RestApi.ApiError');

        return null;
    }
69410
public function onRequestSent(Event $event)
    {
        $request = $event['request'];
        $response = $event['response'];

        if ($request->getParams()->get('cache.hit') === null &&
            $this->canCache->canCacheRequest($request) &&
            $this->canCache->canCacheResponse($response)
        ) {
            $this->storage->cache($request, $response);
        }

        $this->addResponseHeaders($request, $response);
    }
334106
public function onException(GetResponseForExceptionEvent $event)
    {
        if (!$this->eventRequestMatches($event)) {
            return;
        }
        $event->setResponse($this->responseTransformer->createResponseFromContent($event->getException()));
    }
913257
public function respond(Event $event)
    {
        $key = $event->getSubject()->success ? 'success' : 'error';
        $apiConfig = $this->_action()->getConfig('api.' . $key);

        if (isset($apiConfig['exception'])) {
            $this->_exceptionResponse($event, $apiConfig['exception']);

            return null;
        }

        $response = $this->render($event->getSubject());

        if (empty($apiConfig['code'])) {
            return $response;
        }

        return $response->withStatus($apiConfig['code']);
    }
277623
protected function handleError($event)
    {
        if (error_reporting() & $event->code) {
            $this->getSentryClient()->captureException(
                $this->createErrorException($event->message, $event->code, $event->file, $event->line)
            );
        }
        parent::handleError($event);
    }
881764
function handle(Event $event)
    {
        if ($this->accept($event)) {
            $this->onEvent($event);
            return true;
        }

        return false;
    }
1283784
protected function eventWasProcessed($event)
    {
        if ($this->eventExpired($event)) {
            return true;
        }

        $this->resetEventCache($event);

        return false;
    }
712183
private function on403(ErrorEvent $event)
    {
        $url = $event->getRequest()->getUrl();
        $path = parse_url($url, PHP_URL_PATH);
        if ($path && strpos($path, '/api/projects/') === 0) {
            // Clear the environments cache for environment request errors.
            if (preg_match('#^/api/projects/([^/]+?)/environments/#', $path, $matches)) {
                $this->clearEnvironmentsCache($matches[1]);
            }
            // Clear the projects cache for other project request errors.
            if (preg_match('#^/api/projects/([^/]+?)[/$]/#', $path, $matches)) {
                $this->clearProjectsCache();
            }
        }
    }