function ExceptionJsonSubscriber::on4xx

Same name in other branches
  1. 8.9.x core/lib/Drupal/Core/EventSubscriber/ExceptionJsonSubscriber.php \Drupal\Core\EventSubscriber\ExceptionJsonSubscriber::on4xx()
  2. 10 core/lib/Drupal/Core/EventSubscriber/ExceptionJsonSubscriber.php \Drupal\Core\EventSubscriber\ExceptionJsonSubscriber::on4xx()
  3. 11.x core/lib/Drupal/Core/EventSubscriber/ExceptionJsonSubscriber.php \Drupal\Core\EventSubscriber\ExceptionJsonSubscriber::on4xx()

Handles all 4xx errors for JSON.

Parameters

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

File

core/lib/Drupal/Core/EventSubscriber/ExceptionJsonSubscriber.php, line 37

Class

ExceptionJsonSubscriber
Default handling for JSON errors.

Namespace

Drupal\Core\EventSubscriber

Code

public function on4xx(ExceptionEvent $event) {
    
    /** @var \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $exception */
    $exception = $event->getThrowable();
    // If the exception is cacheable, generate a cacheable response.
    if ($exception instanceof CacheableDependencyInterface) {
        $response = new CacheableJsonResponse([
            'message' => $event->getThrowable()
                ->getMessage(),
        ], $exception->getStatusCode(), $exception->getHeaders());
        $response->addCacheableDependency($exception);
    }
    else {
        $response = new JsonResponse([
            'message' => $event->getThrowable()
                ->getMessage(),
        ], $exception->getStatusCode(), $exception->getHeaders());
    }
    $event->setResponse($response);
}

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