function ExceptionJsonSubscriber::on4xx

Same name in other branches
  1. 9 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\GetResponseForExceptionEvent $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(GetResponseForExceptionEvent $event) {
    
    /** @var \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $exception */
    $exception = $event->getException();
    // If the exception is cacheable, generate a cacheable response.
    if ($exception instanceof CacheableDependencyInterface) {
        $response = new CacheableJsonResponse([
            'message' => $event->getException()
                ->getMessage(),
        ], $exception->getStatusCode(), $exception->getHeaders());
        $response->addCacheableDependency($exception);
    }
    else {
        $response = new JsonResponse([
            'message' => $event->getException()
                ->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.