3 namespace Drupal\Core\EventSubscriber;
5 use Drupal\Core\Cache\CacheableDependencyInterface;
6 use Drupal\Core\Cache\CacheableJsonResponse;
7 use Symfony\Component\HttpFoundation\JsonResponse;
8 use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
11 * Default handling for JSON errors.
13 class ExceptionJsonSubscriber extends HttpExceptionSubscriberBase {
18 protected function getHandledFormats() {
19 return ['json', 'drupal_modal', 'drupal_dialog', 'drupal_ajax'];
25 protected static function getPriority() {
26 // This will fire after the most common HTML handler, since HTML requests
27 // are still more common than JSON requests.
32 * Handles all 4xx errors for JSON.
34 * @param \Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event
35 * The event to process.
37 public function on4xx(GetResponseForExceptionEvent $event) {
38 /** @var \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $exception */
39 $exception = $event->getException();
41 // If the exception is cacheable, generate a cacheable response.
42 if ($exception instanceof CacheableDependencyInterface) {
43 $response = new CacheableJsonResponse(['message' => $event->getException()->getMessage()], $exception->getStatusCode(), $exception->getHeaders());
44 $response->addCacheableDependency($exception);
47 $response = new JsonResponse(['message' => $event->getException()->getMessage()], $exception->getStatusCode(), $exception->getHeaders());
50 $event->setResponse($response);