3 namespace Drupal\serialization\EventSubscriber;
5 use Drupal\Core\EventSubscriber\HttpExceptionSubscriberBase;
6 use Symfony\Component\HttpFoundation\Response;
7 use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
8 use Symfony\Component\Serializer\SerializerInterface;
11 * Handles default error responses in serialization formats.
13 class DefaultExceptionSubscriber extends HttpExceptionSubscriberBase {
18 * @var \Symfony\Component\Serializer\Serializer
20 protected $serializer;
23 * The available serialization formats.
27 protected $serializerFormats = [];
30 * DefaultExceptionSubscriber constructor.
32 * @param \Symfony\Component\Serializer\SerializerInterface $serializer
33 * The serializer service.
34 * @param array $serializer_formats
35 * The available serialization formats.
37 public function __construct(SerializerInterface $serializer, array $serializer_formats) {
38 $this->serializer = $serializer;
39 $this->serializerFormats = $serializer_formats;
45 protected function getHandledFormats() {
46 return $this->serializerFormats;
52 protected static function getPriority() {
53 // This will fire after the most common HTML handler, since HTML requests
54 // are still more common than HTTP requests.
59 * Handles all 4xx errors for all serialization failures.
61 * @param \Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event
62 * The event to process.
64 public function on4xx(GetResponseForExceptionEvent $event) {
65 /** @var \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $exception */
66 $exception = $event->getException();
67 $request = $event->getRequest();
69 $format = $request->getRequestFormat();
70 $content = ['message' => $event->getException()->getMessage()];
71 $encoded_content = $this->serializer->serialize($content, $format);
72 $headers = $exception->getHeaders();
74 // Add the MIME type from the request to send back in the header.
75 $headers['Content-Type'] = $request->getMimeType($format);
77 $response = new Response($encoded_content, $exception->getStatusCode(), $headers);
78 $event->setResponse($response);