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

api-platform / core / 14910337627

08 May 2025 03:36PM UTC coverage: 6.873% (-1.6%) from 8.457%
14910337627

Pull #7135

github

web-flow
Merge b0ee9f38d into 613bb5b75
Pull Request #7135: fix(error_status_code): InvalidUriVariableException status code (e400)

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

34 existing lines in 1 file now uncovered.

10887 of 158407 relevant lines covered (6.87%)

6.19 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\ProblemExceptionInterface;
19
use ApiPlatform\Metadata\Exception\StatusAwareExceptionInterface;
20
use ApiPlatform\Metadata\HttpOperation;
21
use ApiPlatform\Metadata\IdentifiersExtractorInterface;
22
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
23
use ApiPlatform\Metadata\ResourceClassResolverInterface;
24
use ApiPlatform\Metadata\Util\ContentNegotiationTrait;
25
use ApiPlatform\State\Util\OperationRequestInitiatorTrait;
26
use Illuminate\Auth\Access\AuthorizationException;
27
use Illuminate\Auth\AuthenticationException;
28
use Illuminate\Contracts\Container\Container;
29
use Illuminate\Foundation\Exceptions\Handler as ExceptionsHandler;
30
use Negotiation\Negotiator;
31
use Symfony\Component\HttpFoundation\Exception\RequestExceptionInterface;
32
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface as SymfonyHttpExceptionInterface;
33
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
34

35
class ErrorHandler extends ExceptionsHandler
36
{
37
    use ContentNegotiationTrait;
38
    use OperationRequestInitiatorTrait;
39

40
    public static mixed $error;
41

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

62
    public function render($request, \Throwable $exception)
63
    {
UNCOV
64
        $apiOperation = $this->initializeOperation($request);
×
65

UNCOV
66
        if (!$apiOperation) {
×
67
            return parent::render($request, $exception);
×
68
        }
69

UNCOV
70
        $formats = $this->errorFormats ?? ['jsonproblem' => ['application/problem+json']];
×
71
        $format = $request->getRequestFormat() ?? $this->getRequestFormat($request, $formats, false);
×
72

UNCOV
73
        if ($this->resourceClassResolver->isResourceClass($exception::class)) {
×
74
            $resourceCollection = $this->resourceMetadataCollectionFactory->create($exception::class);
×
75

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

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

UNCOV
110
            $errorResource = Error::createFromException($exception, $statusCode);
×
111
        }
112

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

119
        // For our swagger Ui errors
UNCOV
120
        if ('html' === $format) {
×
121
            $operation = $operation->withOutputFormats(['html' => ['text/html']]);
×
122
        }
123

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

UNCOV
130
        $normalizationContext = $operation->getNormalizationContext() ?? [];
×
131
        if (!($normalizationContext['api_error_resource'] ?? false)) {
×
132
            $normalizationContext += ['api_error_resource' => true];
×
133
        }
134

UNCOV
135
        if (!isset($normalizationContext[AbstractObjectNormalizer::IGNORED_ATTRIBUTES])) {
×
136
            $normalizationContext[AbstractObjectNormalizer::IGNORED_ATTRIBUTES] = true === $this->debug ? [] : ['originalTrace'];
×
137
        }
138

UNCOV
139
        $operation = $operation->withNormalizationContext($normalizationContext);
×
140

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

UNCOV
154
        foreach ($identifiers as $name => $value) {
×
155
            $dup->attributes->set($name, $value);
×
156
        }
157

158
        try {
UNCOV
159
            return $this->apiPlatformController->__invoke($dup);
×
160
        } catch (\Throwable $e) {
×
161
            return parent::render($dup, $e);
×
162
        }
163
    }
164

165
    private function getStatusCode(?HttpOperation $apiOperation, ?HttpOperation $errorOperation, \Throwable $exception): int
166
    {
UNCOV
167
        $exceptionToStatus = array_merge(
×
168
            $apiOperation ? $apiOperation->getExceptionToStatus() ?? [] : [],
×
169
            $errorOperation ? $errorOperation->getExceptionToStatus() ?? [] : [],
×
170
            $this->exceptionToStatus ?? []
×
171
        );
×
172

UNCOV
173
        foreach ($exceptionToStatus as $class => $status) {
×
174
            if (is_a($exception::class, $class, true)) {
×
175
                return $status;
×
176
            }
177
        }
178

UNCOV
179
        if ($exception instanceof AuthenticationException) {
×
180
            return 401;
×
181
        }
182

UNCOV
183
        if ($exception instanceof AuthorizationException) {
×
184
            return 403;
×
185
        }
186

UNCOV
187
        if ($exception instanceof SymfonyHttpExceptionInterface) {
×
188
            return $exception->getStatusCode();
×
189
        }
190

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

UNCOV
195
        if ($exception instanceof RequestExceptionInterface) {
×
NEW
196
            return 400;
×
197
        }
198

199
        // if ($exception instanceof ValidationException) {
200
        //     return 422;
201
        // }
202

UNCOV
203
        if ($status = $errorOperation?->getStatus()) {
×
204
            return $status;
×
205
        }
206

UNCOV
207
        return 500;
×
208
    }
209

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

222
    public static function provide(): mixed
223
    {
UNCOV
224
        if ($data = static::$error) {
×
225
            return $data;
×
226
        }
227

UNCOV
228
        throw new \LogicException(\sprintf('We could not find the thrown exception in the %s.', self::class));
×
229
    }
230
}
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

© 2026 Coveralls, Inc