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

api-platform / core / 14125142402

28 Mar 2025 08:42AM UTC coverage: 8.512%. Remained the same
14125142402

push

github

web-flow
fix(laravel): error handler only on api routes (#7049)

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

2118 existing lines in 152 files now uncovered.

13385 of 157245 relevant lines covered (8.51%)

22.91 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
     */
45
    public function __construct(
46
        Container $container,
47
        ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory,
48
        private readonly ApiPlatformController $apiPlatformController,
49
        private readonly ?IdentifiersExtractorInterface $identifiersExtractor = null,
50
        private readonly ?ResourceClassResolverInterface $resourceClassResolver = null,
51
        ?Negotiator $negotiator = null,
52
        private readonly ?array $exceptionToStatus = null,
53
        private readonly ?bool $debug = false,
54
        private readonly ?array $errorFormats = null,
55
    ) {
56
        $this->resourceMetadataCollectionFactory = $resourceMetadataCollectionFactory;
×
57
        $this->negotiator = $negotiator;
×
UNCOV
58
        parent::__construct($container);
×
59
    }
60

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

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

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

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

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

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

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

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

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

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

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

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

NEW
138
        $operation = $operation->withNormalizationContext($normalizationContext);
×
139

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

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

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

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

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

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

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

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

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

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

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

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

206
        return 500;
×
207
    }
208

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

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

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