• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

api-platform / core / 15927963363

27 Jun 2025 01:52PM UTC coverage: 22.489% (-0.01%) from 22.5%
15927963363

Pull #7247

github

web-flow
Merge 66de6d385 into d3e73f09a
Pull Request #7247: fix(laravel): decorate error handler

0 of 10 new or added lines in 2 files covered. (0.0%)

8 existing lines in 4 files now uncovered.

11063 of 49194 relevant lines covered (22.49%)

11.03 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/src/Laravel/Exception/ErrorHandler.php
1
<?php
2

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

12
declare(strict_types=1);
13

14
namespace ApiPlatform\Laravel\Exception;
15

16
use ApiPlatform\Laravel\ApiResource\Error;
17
use ApiPlatform\Laravel\Controller\ApiPlatformController;
18
use ApiPlatform\Metadata\Exception\InvalidUriVariableException;
19
use ApiPlatform\Metadata\Exception\ProblemExceptionInterface;
20
use ApiPlatform\Metadata\Exception\StatusAwareExceptionInterface;
21
use ApiPlatform\Metadata\HttpOperation;
22
use ApiPlatform\Metadata\IdentifiersExtractorInterface;
23
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
24
use ApiPlatform\Metadata\ResourceClassResolverInterface;
25
use ApiPlatform\Metadata\Util\ContentNegotiationTrait;
26
use ApiPlatform\State\Util\OperationRequestInitiatorTrait;
27
use Illuminate\Auth\Access\AuthorizationException;
28
use Illuminate\Auth\AuthenticationException;
29
use Illuminate\Contracts\Container\Container;
30
use Illuminate\Contracts\Debug\ExceptionHandler;
31
use Illuminate\Foundation\Exceptions\Handler as ExceptionsHandler;
32
use Negotiation\Negotiator;
33
use Symfony\Component\HttpFoundation\Exception\RequestExceptionInterface;
34
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface as SymfonyHttpExceptionInterface;
35
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
36

37
class ErrorHandler extends ExceptionsHandler
38
{
39
    use ContentNegotiationTrait;
40
    use OperationRequestInitiatorTrait;
41

42
    public static mixed $error;
43

44
    /**
45
     * @param array<class-string, int> $exceptionToStatus
46
     * @param array<string, string[]>  $errorFormats
47
     */
48
    public function __construct(
49
        Container $container,
50
        ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory,
51
        private readonly ApiPlatformController $apiPlatformController,
52
        private readonly ?IdentifiersExtractorInterface $identifiersExtractor = null,
53
        private readonly ?ResourceClassResolverInterface $resourceClassResolver = null,
54
        ?Negotiator $negotiator = null,
55
        private readonly ?array $exceptionToStatus = null,
56
        private readonly ?bool $debug = false,
57
        private readonly ?array $errorFormats = null,
58
        private readonly ?ExceptionHandler $decorated = null
59
    ) {
60
        $this->resourceMetadataCollectionFactory = $resourceMetadataCollectionFactory;
×
61
        $this->negotiator = $negotiator;
×
62
        parent::__construct($container);
×
63
    }
64

65
    public function render($request, \Throwable $exception)
66
    {
67
        $apiOperation = $this->initializeOperation($request);
×
68

69
        if (!$apiOperation) {
×
NEW
70
            return $this->decorated ? $this->decorated->render($request, $exception) : parent::render($request, $exception);
×
71
        }
72

73
        $formats = $this->errorFormats ?? ['jsonproblem' => ['application/problem+json']];
×
74
        $format = $request->getRequestFormat() ?? $this->getRequestFormat($request, $formats, false);
×
75

76
        if ($this->resourceClassResolver->isResourceClass($exception::class)) {
×
77
            $resourceCollection = $this->resourceMetadataCollectionFactory->create($exception::class);
×
78

79
            $operation = null;
×
80
            foreach ($resourceCollection as $resource) {
×
81
                foreach ($resource->getOperations() as $op) {
×
82
                    foreach ($op->getOutputFormats() as $key => $value) {
×
83
                        if ($key === $format) {
×
84
                            $operation = $op;
×
85
                            break 3;
×
86
                        }
87
                    }
88
                }
89
            }
90

91
            // No operation found for the requested format, we take the first available
92
            if (!$operation) {
×
93
                $operation = $resourceCollection->getOperation();
×
94
            }
95
            $errorResource = $exception;
×
96
            if ($errorResource instanceof ProblemExceptionInterface && $operation instanceof HttpOperation) {
×
97
                $statusCode = $this->getStatusCode($apiOperation, $operation, $exception);
×
98
                $operation = $operation->withStatus($statusCode);
×
99
                if ($errorResource instanceof StatusAwareExceptionInterface) {
×
100
                    $errorResource->setStatus($statusCode);
×
101
                }
102
            }
103
        } else {
104
            // Create a generic, rfc7807 compatible error according to the wanted format
105
            $operation = $this->resourceMetadataCollectionFactory->create(Error::class)->getOperation($this->getFormatOperation($format));
×
106
            // status code may be overridden by the exceptionToStatus option
107
            $statusCode = 500;
×
108
            if ($operation instanceof HttpOperation) {
×
109
                $statusCode = $this->getStatusCode($apiOperation, $operation, $exception);
×
110
                $operation = $operation->withStatus($statusCode);
×
111
            }
112

113
            $errorResource = Error::createFromException($exception, $statusCode);
×
114
        }
115

116
        /** @var HttpOperation $operation */
117
        if (!$operation->getProvider()) {
×
118
            static::$error = $errorResource;
×
119
            $operation = $operation->withProvider([self::class, 'provide']);
×
120
        }
121

122
        // For our swagger Ui errors
123
        if ('html' === $format) {
×
124
            $operation = $operation->withOutputFormats(['html' => ['text/html']]);
×
125
        }
126

127
        $identifiers = [];
×
128
        try {
129
            $identifiers = $this->identifiersExtractor?->getIdentifiersFromItem($errorResource, $operation) ?? [];
×
130
        } catch (\Exception $e) {
×
131
        }
132

133
        $normalizationContext = $operation->getNormalizationContext() ?? [];
×
134
        if (!($normalizationContext['api_error_resource'] ?? false)) {
×
135
            $normalizationContext += ['api_error_resource' => true];
×
136
        }
137

138
        if (!isset($normalizationContext[AbstractObjectNormalizer::IGNORED_ATTRIBUTES])) {
×
139
            $normalizationContext[AbstractObjectNormalizer::IGNORED_ATTRIBUTES] = true === $this->debug ? [] : ['originalTrace'];
×
140
        }
141

142
        $operation = $operation->withNormalizationContext($normalizationContext);
×
143

144
        $dup = $request->duplicate(null, null, []);
×
145
        $dup->setMethod('GET');
×
146
        $dup->attributes->set('_api_resource_class', $operation->getClass());
×
147
        $dup->attributes->set('_api_previous_operation', $apiOperation);
×
148
        $dup->attributes->set('_api_operation', $operation);
×
149
        $dup->attributes->set('_api_operation_name', $operation->getName());
×
150
        $dup->attributes->set('exception', $exception);
×
151
        // These are for swagger
152
        $dup->attributes->set('_api_original_route', $request->attributes->get('_route'));
×
153
        $dup->attributes->set('_api_original_uri_variables', $request->attributes->get('_api_uri_variables'));
×
154
        $dup->attributes->set('_api_original_route_params', $request->attributes->get('_route_params'));
×
155
        $dup->attributes->set('_api_requested_operation', $request->attributes->get('_api_requested_operation'));
×
156

157
        foreach ($identifiers as $name => $value) {
×
158
            $dup->attributes->set($name, $value);
×
159
        }
160

161
        try {
NEW
162
            $response = $this->apiPlatformController->__invoke($dup);
×
NEW
163
            $this->decorated->render($dup, $exception);
×
NEW
164
            return $response;
×
165
        } catch (\Throwable $e) {
×
NEW
166
            return $this->decorated ? $this->decorated->render($request, $exception) : parent::render($request, $exception);
×
167
        }
168
    }
169

170
    private function getStatusCode(?HttpOperation $apiOperation, ?HttpOperation $errorOperation, \Throwable $exception): int
171
    {
172
        $exceptionToStatus = array_merge(
×
173
            $apiOperation ? $apiOperation->getExceptionToStatus() ?? [] : [],
×
174
            $errorOperation ? $errorOperation->getExceptionToStatus() ?? [] : [],
×
175
            $this->exceptionToStatus ?? []
×
176
        );
×
177

178
        foreach ($exceptionToStatus as $class => $status) {
×
179
            if (is_a($exception::class, $class, true)) {
×
180
                return $status;
×
181
            }
182
        }
183

184
        if ($exception instanceof AuthenticationException) {
×
185
            return 401;
×
186
        }
187

188
        if ($exception instanceof AuthorizationException) {
×
189
            return 403;
×
190
        }
191

192
        if ($exception instanceof SymfonyHttpExceptionInterface) {
×
193
            return $exception->getStatusCode();
×
194
        }
195

196
        if ($exception instanceof SymfonyHttpExceptionInterface) {
×
197
            return $exception->getStatusCode();
×
198
        }
199

200
        if ($exception instanceof RequestExceptionInterface || $exception instanceof InvalidUriVariableException) {
×
201
            return 400;
×
202
        }
203

204
        // if ($exception instanceof ValidationException) {
205
        //     return 422;
206
        // }
207

208
        if ($status = $errorOperation?->getStatus()) {
×
209
            return $status;
×
210
        }
211

212
        return 500;
×
213
    }
214

215
    private function getFormatOperation(?string $format): string
216
    {
217
        return match ($format) {
×
218
            'json' => '_api_errors_problem',
×
219
            'jsonproblem' => '_api_errors_problem',
×
220
            'jsonld' => '_api_errors_hydra',
×
221
            'jsonapi' => '_api_errors_jsonapi',
×
222
            'html' => '_api_errors_problem', // This will be intercepted by the SwaggerUiProvider
×
223
            default => '_api_errors_problem',
×
224
        };
×
225
    }
226

227
    public static function provide(): mixed
228
    {
229
        if ($data = static::$error) {
×
230
            return $data;
×
231
        }
232

233
        throw new \LogicException(\sprintf('We could not find the thrown exception in the %s.', self::class));
×
234
    }
235
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc