Skip to content

Commit 5a7ca92

Browse files
[HttpKernel] Add HttpException::fromStatusCode()
1 parent c221681 commit 5a7ca92

File tree

4 files changed

+34
-11
lines changed

4 files changed

+34
-11
lines changed

src/Symfony/Component/HttpKernel/CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ CHANGELOG
55
---
66

77
* Add method `isKernelTerminating()` to `ExceptionEvent` that allows to check if an exception was thrown while the kernel is being terminated
8+
* Add `HttpException::fromStatusCode()`
89

910
7.0
1011
---

src/Symfony/Component/HttpKernel/Controller/ArgumentResolver/RequestPayloadValueResolver.php

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,14 @@
1313

1414
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
1515
use Symfony\Component\HttpFoundation\Request;
16-
use Symfony\Component\HttpFoundation\Response;
1716
use Symfony\Component\HttpKernel\Attribute\MapQueryString;
1817
use Symfony\Component\HttpKernel\Attribute\MapRequestPayload;
1918
use Symfony\Component\HttpKernel\Controller\ValueResolverInterface;
2019
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
2120
use Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent;
21+
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
2222
use Symfony\Component\HttpKernel\Exception\HttpException;
23+
use Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException;
2324
use Symfony\Component\HttpKernel\KernelEvents;
2425
use Symfony\Component\Serializer\Exception\NotEncodableValueException;
2526
use Symfony\Component\Serializer\Exception\PartialDenormalizationException;
@@ -124,21 +125,21 @@ public function onKernelControllerArguments(ControllerArgumentsEvent $event): vo
124125
}
125126

126127
if (\count($violations)) {
127-
throw new HttpException($validationFailedCode, implode("\n", array_map(static fn ($e) => $e->getMessage(), iterator_to_array($violations))), new ValidationFailedException($payload, $violations));
128+
throw HttpException::fromStatusCode($validationFailedCode, implode("\n", array_map(static fn ($e) => $e->getMessage(), iterator_to_array($violations))), new ValidationFailedException($payload, $violations));
128129
}
129130
} else {
130131
try {
131132
$payload = $this->$payloadMapper($request, $type, $argument);
132133
} catch (PartialDenormalizationException $e) {
133-
throw new HttpException($validationFailedCode, implode("\n", array_map(static fn ($e) => $e->getMessage(), $e->getErrors())), $e);
134+
throw HttpException::fromStatusCode($validationFailedCode, implode("\n", array_map(static fn ($e) => $e->getMessage(), $e->getErrors())), $e);
134135
}
135136
}
136137

137138
if (null === $payload) {
138139
$payload = match (true) {
139140
$argument->metadata->hasDefaultValue() => $argument->metadata->getDefaultValue(),
140141
$argument->metadata->isNullable() => null,
141-
default => throw new HttpException($validationFailedCode)
142+
default => throw HttpException::fromStatusCode($validationFailedCode)
142143
};
143144
}
144145

@@ -167,11 +168,11 @@ private function mapQueryString(Request $request, string $type, MapQueryString $
167168
private function mapRequestPayload(Request $request, string $type, MapRequestPayload $attribute): ?object
168169
{
169170
if (null === $format = $request->getContentTypeFormat()) {
170-
throw new HttpException(Response::HTTP_UNSUPPORTED_MEDIA_TYPE, 'Unsupported format.');
171+
throw new UnsupportedMediaTypeHttpException('Unsupported format.');
171172
}
172173

173174
if ($attribute->acceptFormat && !\in_array($format, (array) $attribute->acceptFormat, true)) {
174-
throw new HttpException(Response::HTTP_UNSUPPORTED_MEDIA_TYPE, sprintf('Unsupported format, expects "%s", but "%s" given.', implode('", "', (array) $attribute->acceptFormat), $format));
175+
throw new UnsupportedMediaTypeHttpException(sprintf('Unsupported format, expects "%s", but "%s" given.', implode('", "', (array) $attribute->acceptFormat), $format));
175176
}
176177

177178
if ($data = $request->request->all()) {
@@ -183,15 +184,15 @@ private function mapRequestPayload(Request $request, string $type, MapRequestPay
183184
}
184185

185186
if ('form' === $format) {
186-
throw new HttpException(Response::HTTP_BAD_REQUEST, 'Request payload contains invalid "form" data.');
187+
throw new BadRequestHttpException('Request payload contains invalid "form" data.');
187188
}
188189

189190
try {
190191
return $this->serializer->deserialize($data, $type, $format, self::CONTEXT_DESERIALIZE + $attribute->serializationContext);
191192
} catch (UnsupportedFormatException $e) {
192-
throw new HttpException(Response::HTTP_UNSUPPORTED_MEDIA_TYPE, sprintf('Unsupported format: "%s".', $format), $e);
193+
throw new UnsupportedMediaTypeHttpException(sprintf('Unsupported format: "%s".', $format), $e);
193194
} catch (NotEncodableValueException $e) {
194-
throw new HttpException(Response::HTTP_BAD_REQUEST, sprintf('Request payload contains invalid "%s" data.', $format), $e);
195+
throw new BadRequestHttpException(sprintf('Request payload contains invalid "%s" data.', $format), $e);
195196
}
196197
}
197198
}

src/Symfony/Component/HttpKernel/EventListener/ErrorListener.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ public function logKernelException(ExceptionEvent $event): void
6363
}
6464
if (!$throwable instanceof HttpExceptionInterface || $throwable->getStatusCode() !== $config['status_code']) {
6565
$headers = $throwable instanceof HttpExceptionInterface ? $throwable->getHeaders() : [];
66-
$throwable = new HttpException($config['status_code'], $throwable->getMessage(), $throwable, $headers);
66+
$throwable = HttpException::fromStatusCode($config['status_code'], $throwable->getMessage(), $throwable, $headers);
6767
$event->setThrowable($throwable);
6868
}
6969
break;
@@ -78,7 +78,7 @@ public function logKernelException(ExceptionEvent $event): void
7878
/** @var WithHttpStatus $instance */
7979
$instance = $attributes[0]->newInstance();
8080

81-
$throwable = new HttpException($instance->statusCode, $throwable->getMessage(), $throwable, $instance->headers);
81+
$throwable = HttpException::fromStatusCode($instance->statusCode, $throwable->getMessage(), $throwable, $instance->headers);
8282
$event->setThrowable($throwable);
8383
break;
8484
}

src/Symfony/Component/HttpKernel/Exception/HttpException.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,27 @@ public function __construct(int $statusCode, string $message = '', \Throwable $p
2929
parent::__construct($message, $code, $previous);
3030
}
3131

32+
public static function fromStatusCode(int $statusCode, string $message = '', \Throwable $previous = null, array $headers = [], int $code = 0): self
33+
{
34+
return match ($statusCode) {
35+
400 => new BadRequestHttpException($message, $previous, $code, $headers),
36+
403 => new AccessDeniedHttpException($message, $previous, $code, $headers),
37+
404 => new NotFoundHttpException($message, $previous, $code, $headers),
38+
406 => new NotAcceptableHttpException($message, $previous, $code, $headers),
39+
409 => new ConflictHttpException($message, $previous, $code, $headers),
40+
410 => new GoneHttpException($message, $previous, $code, $headers),
41+
411 => new LengthRequiredHttpException($message, $previous, $code, $headers),
42+
412 => new PreconditionFailedHttpException($message, $previous, $code, $headers),
43+
423 => new LockedHttpException($message, $previous, $code, $headers),
44+
415 => new UnsupportedMediaTypeHttpException($message, $previous, $code, $headers),
45+
422 => new UnprocessableEntityHttpException($message, $previous, $code, $headers),
46+
428 => new PreconditionRequiredHttpException($message, $previous, $code, $headers),
47+
429 => new TooManyRequestsHttpException(null, $message, $previous, $code, $headers),
48+
503 => new ServiceUnavailableHttpException(null, $message, $previous, $code, $headers),
49+
default => new static($statusCode, $message, $previous, $headers, $code),
50+
};
51+
}
52+
3253
public function getStatusCode(): int
3354
{
3455
return $this->statusCode;

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy