/
ExceptionAction.php
85 lines (76 loc) · 2.77 KB
/
ExceptionAction.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<?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\Util\ErrorFormatGuesser;
use Symfony\Component\Debug\Exception\FlattenException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\SerializerInterface;
/**
* Renders a normalized exception for a given {@see \Symfony\Component\Debug\Exception\FlattenException}.
*
* Usage:
*
* $exceptionAction = new ExceptionAction(
* new Serializer(),
* [
* 'jsonproblem' => ['application/problem+json'],
* 'jsonld' => ['application/ld+json'],
* ],
* [
* ExceptionInterface::class => Response::HTTP_BAD_REQUEST,
* InvalidArgumentException::class => Response::HTTP_BAD_REQUEST,
* ]
* );
*
* @author Baptiste Meyer <baptiste.meyer@gmail.com>
* @author Kévin Dunglas <dunglas@gmail.com>
*/
final class ExceptionAction
{
private $serializer;
private $errorFormats;
private $exceptionToStatus;
/**
* @param SerializerInterface $serializer
* @param array $errorFormats A list of enabled formats, the first one will be the default
* @param array $exceptionToStatus A list of exceptions mapped to their HTTP status code
*/
public function __construct(SerializerInterface $serializer, array $errorFormats, array $exceptionToStatus = [])
{
$this->serializer = $serializer;
$this->errorFormats = $errorFormats;
$this->exceptionToStatus = $exceptionToStatus;
}
/**
* Converts a an exception to a JSON response.
*
* @param FlattenException $exception
* @param Request $request
*
* @return Response
*/
public function __invoke(FlattenException $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'] = sprintf('%s; charset=utf-8', $format['value'][0]);
$headers['X-Content-Type-Options'] = 'nosniff';
$headers['X-Frame-Options'] = 'deny';
return new Response($this->serializer->serialize($exception, $format['key']), $exception->getStatusCode(), $headers);
}
}