function FinalExceptionSubscriber::on4xx

Same name in other branches
  1. 10 core/lib/Drupal/Core/EventSubscriber/FinalExceptionSubscriber.php \Drupal\Core\EventSubscriber\FinalExceptionSubscriber::on4xx()

Handles all 4xx errors that aren't caught in other exception subscribers.

For example, we catch 406s and 403s generated when handling unsupported formats.

Parameters

\Symfony\Component\HttpKernel\Event\ExceptionEvent $event: The event to process.

File

core/lib/Drupal/Core/EventSubscriber/FinalExceptionSubscriber.php, line 153

Class

FinalExceptionSubscriber
Last-chance handler for exceptions: the final exception subscriber.

Namespace

Drupal\Core\EventSubscriber

Code

public function on4xx(ExceptionEvent $event) {
    $exception = $event->getThrowable();
    if ($exception && $exception instanceof HttpExceptionInterface && str_starts_with((string) $exception->getStatusCode(), '4')) {
        $message = PlainTextOutput::renderFromHtml($exception->getMessage());
        // If the exception is cacheable, generate a cacheable response.
        if ($exception instanceof CacheableDependencyInterface) {
            $response = new CacheableResponse($message, $exception->getStatusCode(), [
                'Content-Type' => 'text/plain',
            ]);
            $response->addCacheableDependency($exception);
        }
        else {
            $response = new Response($message, $exception->getStatusCode(), [
                'Content-Type' => 'text/plain',
            ]);
        }
        $response->headers
            ->add($exception->getHeaders());
        $event->setResponse($response);
    }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.