Skip to content

Commit

Permalink
Catch CouldNotUnserialize exception and continue returning a response (
Browse files Browse the repository at this point in the history
…#408)

* Catch CouldNotUnserialize exception and continue returning a response

* Update CacheResponse.php

* Add back use of hasBeenCached in CacheResponse middleware for readability

* Replace use of Log with report() and fire a CacheMissed event when catching a CouldNotUnserialize exception

Co-authored-by: Freek Van der Herten <[email protected]>
  • Loading branch information
roberttolton and freekmurze authored Nov 25, 2022
1 parent aa67521 commit 48cb5af
Showing 1 changed file with 15 additions and 8 deletions.
23 changes: 15 additions & 8 deletions src/Middlewares/CacheResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Spatie\ResponseCache\Events\CacheMissed;
use Spatie\ResponseCache\Events\ResponseCacheHit;
use Spatie\ResponseCache\Exceptions\CouldNotUnserialize;
use Spatie\ResponseCache\Replacers\Replacer;
use Spatie\ResponseCache\ResponseCache;
use Symfony\Component\HttpFoundation\Response;
Expand All @@ -27,18 +29,23 @@ public function handle(Request $request, Closure $next, ...$args): Response
$tags = $this->getTags($args);

if ($this->responseCache->enabled($request) && ! $this->responseCache->shouldBypass($request)) {
if ($this->responseCache->hasBeenCached($request, $tags)) {
event(new ResponseCacheHit($request));
try {
if ($this->responseCache->hasBeenCached($request, $tags)) {
event(new ResponseCacheHit($request));

$response = $this->responseCache->getCachedResponseFor($request, $tags);
$response = $this->responseCache->getCachedResponseFor($request, $tags);

$response = $this->addCacheAgeHeader($response);
$response = $this->addCacheAgeHeader($response);

$this->getReplacers()->each(function (Replacer $replacer) use ($response) {
$replacer->replaceInCachedResponse($response);
});
$this->getReplacers()->each(function (Replacer $replacer) use ($response) {
$replacer->replaceInCachedResponse($response);
});

return $response;
return $response;
}
} catch (CouldNotUnserialize $e) {
report("Could not unserialize response, returning uncached response instead. Error: {$e->getMessage()}");
event(new CacheMissed($request));
}
}

Expand Down

0 comments on commit 48cb5af

Please sign in to comment.