239e5821160fbed84ca38c0ea17db921a186b7fa
[yaffs-website] / web / core / lib / Drupal / Core / EventSubscriber / ExceptionJsonSubscriber.php
1 <?php
2
3 namespace Drupal\Core\EventSubscriber;
4
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;
9
10 /**
11  * Default handling for JSON errors.
12  */
13 class ExceptionJsonSubscriber extends HttpExceptionSubscriberBase {
14
15   /**
16    * {@inheritdoc}
17    */
18   protected function getHandledFormats() {
19     return ['json', 'drupal_modal', 'drupal_dialog', 'drupal_ajax'];
20   }
21
22   /**
23    * {@inheritdoc}
24    */
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.
28     return -75;
29   }
30
31   /**
32    * Handles all 4xx errors for JSON.
33    *
34    * @param \Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event
35    *   The event to process.
36    */
37   public function on4xx(GetResponseForExceptionEvent $event) {
38     /** @var \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $exception */
39     $exception = $event->getException();
40
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);
45     }
46     else {
47       $response = new JsonResponse(['message' => $event->getException()->getMessage()], $exception->getStatusCode(), $exception->getHeaders());
48     }
49
50     $event->setResponse($response);
51   }
52
53 }