Fast404ExceptionHtmlSubscriber not respecting cacheable metadata of the throwable

Created on 29 September 2024, 7 months ago

Problem/Motivation

When fast404 is enabled and - for example - a CacheableNotFoundHttpException is thrown for a fast404 path, the 404 response does not merge the cacheable metadata of the exception. This results in a 404 page being cached, but unable to invalidate using the cacheable metadata of the thrown exception.

Steps to reproduce

Add a route:

example.txt_file:
  path: '/example.txt'
  defaults:
    _controller: '\Drupal\example\Controller\ExampleController'
    _disable_route_normalizer: 'TRUE'
  requirements:
    # Simple text file allowed to be viewed by everyone.
    _access: 'TRUE'

Simple controller with an __invoke():


namespace Drupal\example\Controller;

use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Http\Exception\CacheableNotFoundHttpException;

class ExampleController extends ControllerBase {

  public function __invoke() {
    $cacheable_metadata = new CacheableMetadata();
    $cacheable_metadata->addCacheTags(['example-tag']);

    throw new CacheableNotFoundHttpException($cacheable_metadata);
  }

}

Visiting the URL will not show the added `example-tag` in the response headers:

HTTP/1.1 404 Not Found
Cache-Tags: 4xx-response http_response config:user.role.anonymous
[ ... ]

Proposed resolution

The solution might be: adding my custom path to the exclude paths of fast404, but to be fair, I think fast404 should respect the cacheable metadata of the throwable too.

# web/core/lib/Drupal/Core/EventSubscriber/Fast404ExceptionHtmlSubscriber.php

class Fast404ExceptionHtmlSubscriber extends HttpExceptionSubscriberBase {

  public function on404(ExceptionEvent $event) {
    # Left out other code for simplicity.

    // Make sure the cache context and tags from the exception are used too.
    $throwable = $event->getThrowable();
    if ($throwable instanceof CacheableDependencyInterface) {
      $response->addCacheableDependency($throwable);
    }

    # [ ... ]
  }

}

Remaining tasks

Writing tests to validate the HTTP response containing the cacheable metadata of the thrown exception.

🐛 Bug report
Status

Active

Version

10.3

Component

request processing system

Created by

🇳🇱Netherlands sanderwind Friesland

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024