You are here

public function ExceptionJsonSubscriber::on4xx in Drupal 8

Same name and namespace in other branches
  1. 9 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);
}