ExceptionJsonSubscriber.php 2.16 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
<?php

namespace Drupal\Core\EventSubscriber;

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;

/**
 * Default handling for JSON errors.
 */
class ExceptionJsonSubscriber extends HttpExceptionSubscriberBase {

  /**
15
   * {@inheritdoc}
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
   */
  protected function getHandledFormats() {
    return ['json'];
  }

  /**
   * {@inheritdoc}
   */
  protected static function getPriority() {
    // This will fire after the most common HTML handler, since HTML requests
    // are still more common than JSON requests.
    return -75;
  }

  /**
   * Handles a 403 error for JSON.
   *
   * @param \Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event
   *   The event to process.
   */
  public function on403(GetResponseForExceptionEvent $event) {
37
    $response = new JsonResponse(array('message' => $event->getException()->getMessage()), Response::HTTP_FORBIDDEN);
38 39 40 41 42 43 44 45 46 47
    $event->setResponse($response);
  }

  /**
   * Handles a 404 error for JSON.
   *
   * @param \Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event
   *   The event to process.
   */
  public function on404(GetResponseForExceptionEvent $event) {
48
    $response = new JsonResponse(array('message' => $event->getException()->getMessage()), Response::HTTP_NOT_FOUND);
49 50 51 52 53 54 55 56 57 58
    $event->setResponse($response);
  }

  /**
   * Handles a 405 error for JSON.
   *
   * @param \Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event
   *   The event to process.
   */
  public function on405(GetResponseForExceptionEvent $event) {
59
    $response = new JsonResponse(array('message' => $event->getException()->getMessage()), Response::HTTP_METHOD_NOT_ALLOWED);
60 61 62
    $event->setResponse($response);
  }

63 64 65 66 67 68 69 70 71 72 73
  /**
   * Handles a 406 error for JSON.
   *
   * @param \Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event
   *   The event to process.
   */
  public function on406(GetResponseForExceptionEvent $event) {
    $response = new JsonResponse(['message' => $event->getException()->getMessage()], Response::HTTP_NOT_ACCEPTABLE);
    $event->setResponse($response);
  }

74
}