DefaultExceptionSubscriber.php in Drupal 9
File
core/modules/jsonapi/src/EventSubscriber/DefaultExceptionSubscriber.php
View source
<?php
namespace Drupal\jsonapi\EventSubscriber;
use Drupal\jsonapi\CacheableResourceResponse;
use Drupal\jsonapi\JsonApiResource\ErrorCollection;
use Drupal\jsonapi\JsonApiResource\JsonApiDocumentTopLevel;
use Drupal\jsonapi\JsonApiResource\LinkCollection;
use Drupal\jsonapi\JsonApiResource\NullIncludedData;
use Drupal\jsonapi\ResourceResponse;
use Drupal\jsonapi\Routing\Routes;
use Drupal\serialization\EventSubscriber\DefaultExceptionSubscriber as SerializationDefaultExceptionSubscriber;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpException;
class DefaultExceptionSubscriber extends SerializationDefaultExceptionSubscriber {
protected static function getPriority() {
return parent::getPriority() + 25;
}
protected function getHandledFormats() {
return [
'api_json',
];
}
public function onException(ExceptionEvent $event) {
if (!$this
->isJsonApiExceptionEvent($event)) {
return;
}
if (($exception = $event
->getThrowable()) && !$exception instanceof HttpException) {
$exception = new HttpException(500, $exception
->getMessage(), $exception);
$event
->setThrowable($exception);
}
$this
->setEventResponse($event, $exception
->getStatusCode());
}
protected function setEventResponse(ExceptionEvent $event, $status) {
$exception = $event
->getThrowable();
$document = new JsonApiDocumentTopLevel(new ErrorCollection([
$exception,
]), new NullIncludedData(), new LinkCollection([]));
if ($event
->getRequest()
->isMethodCacheable()) {
$response = new CacheableResourceResponse($document, $exception
->getStatusCode(), $exception
->getHeaders());
$response
->addCacheableDependency($exception);
}
else {
$response = new ResourceResponse($document, $exception
->getStatusCode(), $exception
->getHeaders());
}
$event
->setResponse($response);
}
protected function isJsonApiExceptionEvent(ExceptionEvent $exception_event) {
$request = $exception_event
->getRequest();
$parameters = $request->attributes
->all();
return $request
->getRequestFormat() === 'api_json' || (bool) Routes::getResourceTypeNameFromParameters($parameters);
}
}