DefaultExceptionSubscriber.php in Drupal 8
File
core/modules/jsonapi/src/EventSubscriber/DefaultExceptionSubscriber.php
View source
<?php
namespace Drupal\jsonapi\EventSubscriber;
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\GetResponseForExceptionEvent;
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(GetResponseForExceptionEvent $event) {
if (!$this
->isJsonApiExceptionEvent($event)) {
return;
}
if (($exception = $event
->getException()) && !$exception instanceof HttpException) {
$exception = new HttpException(500, $exception
->getMessage(), $exception);
$event
->setException($exception);
}
$this
->setEventResponse($event, $exception
->getStatusCode());
}
protected function setEventResponse(GetResponseForExceptionEvent $event, $status) {
$exception = $event
->getException();
$response = new ResourceResponse(new JsonApiDocumentTopLevel(new ErrorCollection([
$exception,
]), new NullIncludedData(), new LinkCollection([])), $exception
->getStatusCode(), $exception
->getHeaders());
$response
->addCacheableDependency($exception);
$event
->setResponse($response);
}
protected function isJsonApiExceptionEvent(GetResponseForExceptionEvent $exception_event) {
$request = $exception_event
->getRequest();
$parameters = $request->attributes
->all();
return $request
->getRequestFormat() === 'api_json' || (bool) Routes::getResourceTypeNameFromParameters($parameters);
}
}