You are here

public function DefaultExceptionSubscriber::on4xx in Drupal 10

Same name and namespace in other branches
  1. 8 core/modules/serialization/src/EventSubscriber/DefaultExceptionSubscriber.php \Drupal\serialization\EventSubscriber\DefaultExceptionSubscriber::on4xx()
  2. 9 core/modules/serialization/src/EventSubscriber/DefaultExceptionSubscriber.php \Drupal\serialization\EventSubscriber\DefaultExceptionSubscriber::on4xx()

Handles all 4xx errors for all serialization failures.

Parameters

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

File

core/modules/serialization/src/EventSubscriber/DefaultExceptionSubscriber.php, line 70

Class

DefaultExceptionSubscriber
Handles default error responses in serialization formats.

Namespace

Drupal\serialization\EventSubscriber

Code

public function on4xx(ExceptionEvent $event) {

  /** @var \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $exception */
  $exception = $event
    ->getThrowable();
  $request = $event
    ->getRequest();
  $format = $request
    ->getRequestFormat();
  $content = [
    'message' => $exception
      ->getMessage(),
  ];
  $encoded_content = $this->serializer
    ->serialize($content, $format);
  $headers = $exception
    ->getHeaders();

  // Add the MIME type from the request to send back in the header.
  $headers['Content-Type'] = $request
    ->getMimeType($format);

  // If the exception is cacheable, generate a cacheable response.
  if ($exception instanceof CacheableDependencyInterface) {
    $response = new CacheableResponse($encoded_content, $exception
      ->getStatusCode(), $headers);
    $response
      ->addCacheableDependency($exception);
  }
  else {
    $response = new Response($encoded_content, $exception
      ->getStatusCode(), $headers);
  }
  $event
    ->setResponse($response);
}