function DefaultExceptionSubscriber::on4xx

Same name in other branches
  1. 9 core/modules/serialization/src/EventSubscriber/DefaultExceptionSubscriber.php \Drupal\serialization\EventSubscriber\DefaultExceptionSubscriber::on4xx()
  2. 10 core/modules/serialization/src/EventSubscriber/DefaultExceptionSubscriber.php \Drupal\serialization\EventSubscriber\DefaultExceptionSubscriber::on4xx()
  3. 11.x 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\GetResponseForExceptionEvent $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(GetResponseForExceptionEvent $event) {
    
    /** @var \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $exception */
    $exception = $event->getException();
    $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);
}

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