annotate core/lib/Drupal/Core/EventSubscriber/ExceptionJsonSubscriber.php @ 19:fa3358dc1485 tip

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