If possible, return a cache response on an error

@param Event $event
778234
public function onRequestError(Event $event)
    {
        $request = $event['request'];

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

        if ($response = $this->storage->fetch($request)) {
            $response->setHeader(
                'Age',
                time() - strtotime($response->getLastModified() ? : $response->getDate() ?: 'now')
            );

            if ($this->canResponseSatisfyFailedRequest($request, $response)) {
                $request->getParams()->set('cache.hit', 'error');
                $this->addResponseHeaders($request, $response);
                $event['response'] = $response;
                $event->stopPropagation();
            }
        }
    }
917320
public function forget(Event $event)
    {
        $this->cache->store($this->store)->forget($event->mutexName());
    }
688561
private function getPageNotFoundException(GetResponseForExceptionEvent $event)
    {
        $exception = $event->getException();

        if ($exception instanceof PageNotFoundException) {
            return $exception;
        }
        if ($exception->getPrevious() instanceof PageNotFoundException) {
            return $exception->getPrevious();
        }

        return null;
    }
531268
public function onException(GetResponseForExceptionEvent $event)
    {
        if (!$this->isApplicable($event->getRequest())) {
            return;
        }

        $response = $this->convert($event->getException());

        $event->setResponse($response);
    }
1117911
public function onError(ErrorEvent $event)
    {
        $request = $event->getRequest();
        $response = $event->getResponse();

        // Only sign requests using "auth"="oauth"
        if ('oauth' !== $request->getConfig()['auth']) {
            return;
        }

        // Only deal with Unauthorized response.
        if ($response && $response->getStatusCode() != 401) {
            return;
        }

        // If we already retried once, give up.
        if ($request->getHeader('X-Guzzle-Retry')) {
            return;
        }

        // Delete the previous access token, if any
        $this->deleteAccessToken();

        // Acquire a new access token, and retry the request.
        $accessToken = $this->getAccessToken();
        if ($accessToken != null) {
            $newRequest = clone $request;
            $newRequest->setHeader('X-Guzzle-Retry', '1');

            $this->accessTokenSigner->sign($newRequest, $accessToken);

            $event->intercept(
                $event->getClient()->send($newRequest)
            );
        }
    }
801068
public function onRequestComplete(Event $event)
    {
        $response = $event['response'];

        if (!$contentMd5 = $response->getContentMd5()) {
            return;
        }

        $contentEncoding = $response->getContentEncoding();
        if ($contentEncoding && !$this->contentEncoded) {
            return false;
        }

        // Make sure that the size of the request is under the cutoff size
        if ($this->contentLengthCutoff) {
            $size = $response->getContentLength() ?: $response->getBody()->getSize();
            if (!$size || $size > $this->contentLengthCutoff) {
                return;
            }
        }

        if (!$contentEncoding) {
            $hash = $response->getBody()->getContentMd5();
        } elseif ($contentEncoding == 'gzip') {
            $response->getBody()->compress('zlib.deflate');
            $hash = $response->getBody()->getContentMd5();
            $response->getBody()->uncompress();
        } elseif ($contentEncoding == 'compress') {
            $response->getBody()->compress('bzip2.compress');
            $hash = $response->getBody()->getContentMd5();
            $response->getBody()->uncompress();
        } else {
            return;
        }

        if ($contentMd5 !== $hash) {
            throw new UnexpectedValueException(
                "The response entity body may have been modified over the wire.  The Content-MD5 "
                . "received ({$contentMd5}) did not match the calculated MD5 hash ({$hash})."
            );
        }
    }
140063
public function onRequestError(Event $event)
    {
        // if token validity expired, re-request with a new token.
        if (in_array($event['response']->getStatusCode(), array(401, 403))) {
            /** @var \Guzzle\Http\Message\Request $request */
            $request = $event['request'];

            // if this is the token-url, stop now because we won't be able to fetch a token
            if ($request->getUrl() === $request->getClient()->getTokenUrl()) {
                return;
            }

            // see if we have retries left
            if ($request->hasHeader('X-Auth-Retries')) {
                $headerValues = $request->getHeader('X-Auth-Retries')->toArray();
                $retriesValue = array_shift($headerValues);
            }

            $retries = $request->hasHeader('X-Auth-Retries') ? $retriesValue : 1;
            if ($retries < 1) {
                if ($this->logger) {
                    $this->logger->addError('Keystone request failed, no more retries left');
                }

                return;
            }

            if ($this->logger) {
                $this->logger->addDebug('Token expired, fetching a new one');
            }

            // set new token in client
            $client = $request->getClient();
            $this->resetToken($client);

            // clone request and update token header
            $newRequest = clone $request;
            $newRequest->setHeader('X-Auth-Token', $client->getToken()->getId());
            $newRequest->setHeader('X-Auth-Retries', --$retries);
            $newResponse = $newRequest->send();

            // Set the response object of the request without firing more events
            $event['response'] = $newResponse;

            // Stop other events from firing when you override 401 responses
            $event->stopPropagation();
        }
    }
406532
protected function doWrite(array $event)
    {
        $client = $this->initHttpClient($this->uri, $this->options);
        $serialisedData = serialize($event);
        $rawData = base64_encode($serialisedData);
        $client->setRawBody($rawData);
        $response = $client->send();

        if ($response->isServerError()) {
            throw new \RuntimeException(
                sprintf(
                    'Error with status %s by send event to %s, with message: %s',
                    $response->getStatusCode(),
                    $this->uri,
                    $response->getReasonPhrase()
                )
            );
        }
    }
1011092
final private function replayChange(Event $event)
    {
        $this->apply($event->payload());
        $this->lastCommittedEventSequenceNumber = $event->sequenceNumber();
    }
468944
public function fetch(FilterRequestEvent $event)
    {
        if ($this->cache === null) {
            return null;
        }
        $request = $event->getRequest();
        if (!$this->cache->has($request->getUrl())) {
            return null;
        }
        /** @var $response CachedResponse */
        $response = $this->cache->get($request->getUrl());
        if (empty($response)) {
            return null;
        }
        $this->log->write(Log::INFO, 'HTTPCache', 'Cache hit for path: %s', $request->getUrl());
        $this->from_cache = true;

        $main = $this->container->get('Miny\\HTTP\\Response');
        foreach ($response->getParts() as $part) {
            if ($part instanceof CachedResponse) {
                $main->addResponse(
                    $this->container->get('Miny\\Application\\Dispatcher')->dispatch(
                        $part->getRequest()
                    )
                );
            } else {
                $main->addContent($part);
            }
        }

        return $response;
    }
1036995
public function onKernelException(GetResponseForExceptionEvent $event)
    {
        if (($exception = $event->getException()) instanceof NotFoundException) {
            $msg = array("message" => $exception->getMessage());
            // Set status code and content
            $response = $exception->getResponse();
            if (!$response instanceof Response) {
                $response = new Response();
            }

            $response = $response
                ->setStatusCode(Response::HTTP_NOT_FOUND)
                ->setContent($this->getSerializedContent($msg));

            $event->setResponse($response);
        }
    }
1228410
private function getEventLevel(Event $event)
    {
        $type = $event->getType();

        switch ($type) {
            case Event::INFO:    return LogLevel::INFO;
            case Event::SUCCESS: return LogLevel::NOTICE;
            case Event::WARNING: return LogLevel::WARNING;
            case Event::ERROR:   return LogLevel::ERROR;
        }

        throw new \InvalidArgumentException("$type is not a valid event type");
    }
843340
private function getEventObject(Event $event)
    {
        // get the service name
        list ($serviceName) = explode(":", $event->getRequest()->get('_controller'));

        // get the controller which handles this request
        if ($this->container->has($serviceName)) {
            $controller = $this->container->get($serviceName);
            $restEvent = $this->restEvent;
            $restEvent->setRequest($event->getRequest());
            $restEvent->setResponse($this->response);
            $restEvent->setController($controller);

            $returnEvent = $restEvent;
        } else {
            $returnEvent = $event;
        }

        return $returnEvent;
    }
1304844
public function onKernelException(GetResponseForExceptionEvent $event) {

        $ex = $event->getException();

        // Handle the exception.
        if (true === ($ex instanceof BadUserRoleException)) {
            $this->handleBadUserRoleException($event, $ex);
        }
        if (true === ($ex instanceof RedirectResponseException)) {
            $this->handleRedirectResponseException($event, $ex);
        }

        return $event;
    }
745557
public static function onRequestError(Event $event)
    {
        $e = BadResponseException::factory($event['request'], $event['response']);
        $event['request']->setState(self::STATE_ERROR, array('exception' => $e) + $event->toArray());
        throw $e;
    }
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);
        }
    }
1360305
public function onRequestSuccess(Event $event)
    {
        /** @var Response $response */
        $response = $event['response'];

        if (!$response->hasHeader('X-RateLimit-Limit')) {
            $this->rateLimitEnabled = false;

            return;
        }

        $this->rateLimitMax = (string) $response->getHeader('X-RateLimit-Limit');

        if ($response->hasHeader('X-RateLimit-Remaining')) {
            $this->rateLimitRemaining = (string) $response->getHeader('X-RateLimit-Remaining');
        }

        if ($response->hasHeader('X-RateLimit-Reset')) {
            $this->rateLimitReset = (string) $response->getHeader('X-RateLimit-Reset');
        }

        // Prevent division by zero
        if ($this->rateLimitMax == 0) {
            $this->rateLimitMax = 1;
        }
    }