ExceptionJsonSubscriber.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. namespace Drupal\Core\EventSubscriber;
  3. use Drupal\Core\Cache\CacheableDependencyInterface;
  4. use Drupal\Core\Cache\CacheableJsonResponse;
  5. use Symfony\Component\HttpFoundation\JsonResponse;
  6. use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
  7. /**
  8. * Default handling for JSON errors.
  9. */
  10. class ExceptionJsonSubscriber extends HttpExceptionSubscriberBase {
  11. /**
  12. * {@inheritdoc}
  13. */
  14. protected function getHandledFormats() {
  15. return ['json', 'drupal_modal', 'drupal_dialog', 'drupal_ajax'];
  16. }
  17. /**
  18. * {@inheritdoc}
  19. */
  20. protected static function getPriority() {
  21. // This will fire after the most common HTML handler, since HTML requests
  22. // are still more common than JSON requests.
  23. return -75;
  24. }
  25. /**
  26. * Handles all 4xx errors for JSON.
  27. *
  28. * @param \Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event
  29. * The event to process.
  30. */
  31. public function on4xx(GetResponseForExceptionEvent $event) {
  32. /** @var \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $exception */
  33. $exception = $event->getException();
  34. // If the exception is cacheable, generate a cacheable response.
  35. if ($exception instanceof CacheableDependencyInterface) {
  36. $response = new CacheableJsonResponse(['message' => $event->getException()->getMessage()], $exception->getStatusCode(), $exception->getHeaders());
  37. $response->addCacheableDependency($exception);
  38. }
  39. else {
  40. $response = new JsonResponse(['message' => $event->getException()->getMessage()], $exception->getStatusCode(), $exception->getHeaders());
  41. }
  42. $event->setResponse($response);
  43. }
  44. }