diff --git a/Serializer/ErrorNormalizer.php b/Serializer/ErrorNormalizer.php index 19764af..6249a07 100644 --- a/Serializer/ErrorNormalizer.php +++ b/Serializer/ErrorNormalizer.php @@ -13,7 +13,6 @@ namespace ApiPlatform\JsonApi\Serializer; -use ApiPlatform\Problem\Serializer\ErrorNormalizerTrait; use ApiPlatform\Serializer\CacheableSupportsMethodInterface; use ApiPlatform\Symfony\Validator\Exception\ConstraintViolationListAwareExceptionInterface as LegacyConstraintViolationListAwareExceptionInterface; use ApiPlatform\Validator\Exception\ConstraintViolationListAwareExceptionInterface; diff --git a/Serializer/ErrorNormalizerTrait.php b/Serializer/ErrorNormalizerTrait.php new file mode 100644 index 0000000..73bfd13 --- /dev/null +++ b/Serializer/ErrorNormalizerTrait.php @@ -0,0 +1,52 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\JsonApi\Serializer; + +use Symfony\Component\ErrorHandler\Exception\FlattenException; +use Symfony\Component\HttpFoundation\Response; + +trait ErrorNormalizerTrait +{ + private function getErrorMessage($object, array $context, bool $debug = false): string + { + $message = $object->getMessage(); + + if ($debug) { + return $message; + } + + if ($object instanceof FlattenException) { + $statusCode = $context['statusCode'] ?? $object->getStatusCode(); + if ($statusCode >= 500 && $statusCode < 600) { + $message = Response::$statusTexts[$statusCode] ?? Response::$statusTexts[Response::HTTP_INTERNAL_SERVER_ERROR]; + } + } + + return $message; + } + + private function getErrorCode(object $object): ?string + { + if ($object instanceof FlattenException) { + return (string)$object->getStatusCode(); + } + + if ($object instanceof \Exception) { + $code = $object->getCode(); + return $code !== 0 ? (string)$code : null; + } + + return null; + } +}