Chris@0: serializer = $serializer; Chris@0: $this->serializerFormats = $serializer_formats; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: protected function getHandledFormats() { Chris@0: return $this->serializerFormats; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: protected static function getPriority() { Chris@0: // This will fire after the most common HTML handler, since HTML requests Chris@14: // are still more common than HTTP requests. But it has a lower priority Chris@14: // than \Drupal\Core\EventSubscriber\ExceptionJsonSubscriber::on4xx(), so Chris@14: // that this also handles the 'json' format. Then all serialization formats Chris@14: // (::getHandledFormats()) are handled by this exception subscriber, which Chris@14: // results in better consistency. Chris@14: return -70; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Handles all 4xx errors for all serialization failures. Chris@0: * Chris@0: * @param \Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event Chris@0: * The event to process. Chris@0: */ Chris@0: public function on4xx(GetResponseForExceptionEvent $event) { Chris@0: /** @var \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $exception */ Chris@0: $exception = $event->getException(); Chris@0: $request = $event->getRequest(); Chris@0: Chris@0: $format = $request->getRequestFormat(); Chris@14: $content = ['message' => $exception->getMessage()]; Chris@0: $encoded_content = $this->serializer->serialize($content, $format); Chris@0: $headers = $exception->getHeaders(); Chris@0: Chris@0: // Add the MIME type from the request to send back in the header. Chris@0: $headers['Content-Type'] = $request->getMimeType($format); Chris@0: Chris@14: // If the exception is cacheable, generate a cacheable response. Chris@14: if ($exception instanceof CacheableDependencyInterface) { Chris@14: $response = new CacheableResponse($encoded_content, $exception->getStatusCode(), $headers); Chris@14: $response->addCacheableDependency($exception); Chris@14: } Chris@14: else { Chris@14: $response = new Response($encoded_content, $exception->getStatusCode(), $headers); Chris@14: } Chris@14: Chris@0: $event->setResponse($response); Chris@0: } Chris@0: Chris@0: }