ExceptionJsonSubscriber.php in Drupal 9
File
core/lib/Drupal/Core/EventSubscriber/ExceptionJsonSubscriber.php
View source
<?php
namespace Drupal\Core\EventSubscriber;
use Drupal\Core\Cache\CacheableDependencyInterface;
use Drupal\Core\Cache\CacheableJsonResponse;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
class ExceptionJsonSubscriber extends HttpExceptionSubscriberBase {
protected function getHandledFormats() {
return [
'json',
'drupal_modal',
'drupal_dialog',
'drupal_ajax',
];
}
protected static function getPriority() {
return -75;
}
public function on4xx(ExceptionEvent $event) {
$exception = $event
->getThrowable();
if ($exception instanceof CacheableDependencyInterface) {
$response = new CacheableJsonResponse([
'message' => $event
->getThrowable()
->getMessage(),
], $exception
->getStatusCode(), $exception
->getHeaders());
$response
->addCacheableDependency($exception);
}
else {
$response = new JsonResponse([
'message' => $event
->getThrowable()
->getMessage(),
], $exception
->getStatusCode(), $exception
->getHeaders());
}
$event
->setResponse($response);
}
}