Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions features/problem.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
Feature: Error handling valid according to RFC 7807 (application/problem+json)
In order to be able to handle error client side
As a client software developer
I need to retrieve an RFC 7807 compliant serialization of errors

Scenario: Get an error
When I add "Accept" header equal to "application/json"
And I send a "POST" request to "/dummies" with body:
"""
{}
"""
Then the response status code should be 400
And the response should be in JSON
And the header "Content-Type" should be equal to "application/problem+json"
And the JSON should be equal to:
"""
{
"type": "https://tools.ietf.org/html/rfc2616#section-10",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

RFC 2616 is obsolete. See RFC 7231 instead.

Copy link
Contributor

@teohhanhui teohhanhui Jul 18, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So this should be (if we use specific URIs for each status code):

    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1"

p/s: The indentation in this section is wrong (3 spaces instead of the intended 4)

"title": "An error occurred",
"detail": "name: This value should not be blank.",
"violations": [
{
"propertyPath": "name",
"message": "This value should not be blank."
}
]
}
"""

Scenario: Get an error during deserialization of simple relation
When I add "Accept" header equal to "application/json"
And I send a "POST" request to "/dummies" with body:
"""
{
"name": "Foo",
"relatedDummy": {
"name": "bar"
}
}
"""
Then the response status code should be 400
And the response should be in JSON
And the header "Content-Type" should be equal to "application/problem+json"
And the JSON node "type" should be equal to "https://tools.ietf.org/html/rfc2616#section-10"
And the JSON node "title" should be equal to "An error occurred"
And the JSON node "detail" should be equal to 'Nested objects for attribute "relatedDummy" of "ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\Dummy" are not enabled. Use serialization groups to change that behavior.'
And the JSON node "trace" should exist
71 changes: 71 additions & 0 deletions src/Action/ExceptionAction.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace ApiPlatform\Core\Action;

use ApiPlatform\Core\Exception\InvalidArgumentException;
use ApiPlatform\Core\Util\ErrorFormatGuesser;
use Symfony\Component\Debug\Exception\FlattenException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\Exception\ExceptionInterface;
use Symfony\Component\Serializer\SerializerInterface;

/**
* Renders a normalized exception for a given {@see \Symfony\Component\Debug\Exception\FlattenException}.
*
* @author Baptiste Meyer <baptiste.meyer@gmail.com>
* @author Kévin Dunglas <dunglas@gmail.com>
*/
final class ExceptionAction
{
const DEFAULT_EXCEPTION_TO_STATUS = [
ExceptionInterface::class => Response::HTTP_BAD_REQUEST,
InvalidArgumentException::class => Response::HTTP_BAD_REQUEST,
];

private $serializer;
private $errorFormats;
private $exceptionToStatus;

public function __construct(SerializerInterface $serializer, array $errorFormats, $exceptionToStatus = [])
{
$this->serializer = $serializer;
$this->errorFormats = $errorFormats;
$this->exceptionToStatus = array_merge(self::DEFAULT_EXCEPTION_TO_STATUS, $exceptionToStatus);
}

/**
* Converts a an exception to a JSON response.
*
* @param \Exception|FlattenException $exception
* @param Request $request
*
* @return Response
*/
public function __invoke($exception, Request $request) : Response
{
$exceptionClass = $exception->getClass();
foreach ($this->exceptionToStatus as $class => $status) {
if (is_a($exceptionClass, $class, true)) {
$exception->setStatusCode($status);

break;
}
}

$headers = $exception->getHeaders();
$format = ErrorFormatGuesser::guessErrorFormat($request, $this->errorFormats);
$headers['Content-Type'] = $format['value'][0];

return new Response($this->serializer->serialize($exception, $format['key']), $exception->getStatusCode(), $headers);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -53,23 +53,20 @@ public function load(array $configs, ContainerBuilder $container)
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);

$formats = [];
foreach ($config['formats'] as $format => $value) {
foreach ($value['mime_types'] as $mimeType) {
$formats[$format][] = $mimeType;
}
}

$container->setAlias('api_platform.naming.resource_path_naming_strategy', $config['naming']['resource_path_naming_strategy']);

if ($config['name_converter']) {
$container->setAlias('api_platform.name_converter', $config['name_converter']);
}

$formats = $this->getFormats($config['formats']);
$errorFormats = $this->getFormats($config['error_formats']);

$container->setParameter('api_platform.title', $config['title']);
$container->setParameter('api_platform.description', $config['description']);
$container->setParameter('api_platform.version', $config['version']);
$container->setParameter('api_platform.formats', $formats);
$container->setParameter('api_platform.error_formats', $errorFormats);
$container->setParameter('api_platform.collection.order', $config['collection']['order']);
$container->setParameter('api_platform.collection.order_parameter_name', $config['collection']['order_parameter_name']);
$container->setParameter('api_platform.collection.pagination.enabled', $config['collection']['pagination']['enabled']);
Expand Down Expand Up @@ -99,6 +96,10 @@ public function load(array $configs, ContainerBuilder $container)
$loader->load('hal.xml');
}

if (isset($errorFormats['jsonproblem'])) {
$loader->load('problem.xml');
}

$this->registerAnnotationLoaders($container);
$this->registerFileLoaders($container);

Expand Down Expand Up @@ -179,4 +180,23 @@ private function registerFileLoaders(ContainerBuilder $container)
$container->getDefinition('api_platform.metadata.resource.name_collection_factory.xml')->replaceArgument(0, $xmlResources);
$container->getDefinition('api_platform.metadata.resource.metadata_factory.xml')->replaceArgument(0, $xmlResources);
}

/**
* Normalizes the format from config to the one accepted by Symfony HttpFoundation.
*
* @param array $configFormats
*
* @return array
*/
private function getFormats(array $configFormats) : array
{
$formats = [];
foreach ($configFormats as $format => $value) {
foreach ($value['mime_types'] as $mimeType) {
$formats[$format][] = $mimeType;
}
}

return $formats;
}
}
71 changes: 46 additions & 25 deletions src/Bridge/Symfony/Bundle/DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

namespace ApiPlatform\Core\Bridge\Symfony\Bundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

Expand All @@ -34,31 +35,6 @@ public function getConfigTreeBuilder()
->scalarNode('title')->defaultValue('')->info('The title of the API.')->end()
->scalarNode('description')->defaultValue('')->info('The description of the API.')->end()
->scalarNode('version')->defaultValue('0.0.0')->info('The version of the API.')->end()
->arrayNode('formats')
->defaultValue(['jsonld' => ['mime_types' => ['application/ld+json']]])
->info('The list of enabled formats. The first one will be the default.')
->normalizeKeys(false)
->useAttributeAsKey('format')
->beforeNormalization()
->ifArray()
->then(function ($v) {
foreach ($v as $format => $value) {
if (isset($value['mime_types'])) {
continue;
}

$v[$format] = ['mime_types' => $value];
}

return $v;
})
->end()
->prototype('array')
->children()
->arrayNode('mime_types')->prototype('scalar')->end()->end()
->end()
->end()
->end()
->arrayNode('naming')
->addDefaultsIfNotSet()
->children()
Expand Down Expand Up @@ -92,6 +68,51 @@ public function getConfigTreeBuilder()
->end()
->end();

$this->addFormatSection($rootNode, 'formats', ['jsonld' => ['mime_types' => ['application/ld+json']]]);
$this->addFormatSection($rootNode, 'error_formats', [
'jsonproblem' => ['mime_types' => ['application/problem+json']],
'jsonld' => ['mime_types' => ['application/ld+json']],
]);

return $treeBuilder;
}

/**
* Adds a format section.
*
* @param ArrayNodeDefinition $rootNode
* @param string $key
* @param array $defaultValue
*/
private function addFormatSection(ArrayNodeDefinition $rootNode, string $key, array $defaultValue)
{
$rootNode
->children()
->arrayNode($key)
->defaultValue($defaultValue)
->info('The list of enabled formats. The first one will be the default.')
->normalizeKeys(false)
->useAttributeAsKey('format')
->beforeNormalization()
->ifArray()
->then(function ($v) {
foreach ($v as $format => $value) {
if (isset($value['mime_types'])) {
continue;
}

$v[$format] = ['mime_types' => $value];
}

return $v;
})
->end()
->prototype('array')
->children()
->arrayNode('mime_types')->prototype('scalar')->end()->end()
->end()
->end()
->end()
->end();
}
}
20 changes: 20 additions & 0 deletions src/Bridge/Symfony/Bundle/Resources/config/api.xml
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,21 @@
<tag name="kernel.event_listener" event="kernel.view" method="onKernelView" priority="8" />
</service>

<service id="api_platform.listener.exception.validation" class="ApiPlatform\Core\Bridge\Symfony\Validator\EventListener\ValidationExceptionListener">
<argument type="service" id="api_platform.serializer" />
<argument>%api_platform.error_formats%</argument>

<tag name="kernel.event_listener" event="kernel.exception" method="onKernelException" />
</service>

<service id="api_platform.listener.exception" class="ApiPlatform\Core\EventListener\ExceptionListener">
<argument>api_platform.action.exception</argument>
<argument type="service" id="logger" on-invalid="null" />

<tag name="kernel.event_listener" event="kernel.exception" method="onKernelException" priority="-96" />
<tag name="monolog.logger" channel="request" />
</service>

<!-- Action -->

<service id="api_platform.action.placeholder" class="ApiPlatform\Core\Action\PlaceholderAction" />
Expand All @@ -120,6 +135,11 @@
<service id="api_platform.action.entrypoint" class="ApiPlatform\Core\Action\EntrypointAction">
<argument type="service" id="api_platform.metadata.resource.name_collection_factory" />
</service>

<service id="api_platform.action.exception" class="ApiPlatform\Core\Action\ExceptionAction">
<argument type="service" id="api_platform.serializer" />
<argument>%api_platform.error_formats%</argument>
</service>
</services>

</container>
41 changes: 11 additions & 30 deletions src/Bridge/Symfony/Bundle/Resources/config/hydra.xml
Original file line number Diff line number Diff line change
Expand Up @@ -25,22 +25,14 @@
<tag name="kernel.event_listener" event="kernel.response" method="onKernelResponse" />
</service>

<service id="api_platform.hydra.listener.exception.validation" class="ApiPlatform\Core\Bridge\Symfony\Validator\Hydra\EventListener\ValidationExceptionListener">
<argument type="service" id="api_platform.hydra.normalizer.constraint_violation_list" />

<tag name="kernel.event_listener" event="kernel.exception" method="onKernelException" />
</service>
<!-- Serializer -->

<service id="api_platform.hydra.listener.exception" class="ApiPlatform\Core\Hydra\EventListener\ExceptionListener">
<argument>api_platform.hydra.action.exception</argument>
<argument type="service" id="logger" on-invalid="null" />
<service id="api_platform.hydra.normalizer.constraint_violation_list" class="ApiPlatform\Core\Hydra\Serializer\ConstraintViolationListNormalizer" public="false">
<argument type="service" id="api_platform.router" />

<tag name="kernel.event_listener" event="kernel.exception" method="onKernelException" priority="-96" />
<tag name="monolog.logger" channel="request" />
<tag name="serializer.normalizer" priority="64" />
</service>

<!-- Serializer -->

<service id="api_platform.hydra.normalizer.resource_name_collection" class="ApiPlatform\Core\Hydra\Serializer\ResourceNameCollectionNormalizer" public="false">
<argument type="service" id="api_platform.metadata.resource.metadata_factory" />
<argument type="service" id="api_platform.iri_converter" />
Expand All @@ -49,6 +41,13 @@
<tag name="serializer.normalizer" priority="32" />
</service>

<service id="api_platform.hydra.normalizer.error" class="ApiPlatform\Core\Hydra\Serializer\ErrorNormalizer" public="false">
<argument type="service" id="api_platform.router" />
<argument>%kernel.debug%</argument>

<tag name="serializer.normalizer" priority="32" />
</service>

<service id="api_platform.hydra.normalizer.collection" class="ApiPlatform\Core\Hydra\Serializer\CollectionNormalizer" public="false">
<argument type="service" id="api_platform.jsonld.context_builder" />
<argument type="service" id="api_platform.resource_class_resolver" />
Expand All @@ -57,19 +56,6 @@
<tag name="serializer.normalizer" priority="16" />
</service>

<service id="api_platform.hydra.normalizer.constraint_violation_list" class="ApiPlatform\Core\Bridge\Symfony\Validator\Hydra\Serializer\ConstraintViolationListNormalizer" public="false">
<argument type="service" id="api_platform.router" />

<tag name="serializer.normalizer" />
</service>

<service id="api_platform.hydra.normalizer.error" class="ApiPlatform\Core\Hydra\Serializer\ErrorNormalizer" public="false">
<argument type="service" id="api_platform.router" />
<argument>%kernel.debug%</argument>

<tag name="serializer.normalizer" />
</service>

<service id="api_platform.hydra.normalizer.partial_collection_view" class="ApiPlatform\Core\Hydra\Serializer\PartialCollectionViewNormalizer" decorates="api_platform.hydra.normalizer.collection" public="false">
<argument type="service" id="api_platform.hydra.normalizer.partial_collection_view.inner" />
<argument>%api_platform.collection.pagination.page_parameter_name%</argument>
Expand All @@ -88,11 +74,6 @@
<service id="api_platform.hydra.action.documentation" class="ApiPlatform\Core\Documentation\Action\DocumentationAction">
<argument type="service" id="api_platform.hydra.documentation_builder" />
</service>

<service id="api_platform.hydra.action.exception" class="ApiPlatform\Core\Hydra\Action\ExceptionAction">
<argument type="service" id="api_platform.hydra.normalizer.error" />
</service>

</services>

</container>
Loading