Skip to content

Instantly share code, notes, and snippets.

@Jibbarth
Created April 10, 2024 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jibbarth/8b153ed3b1ffc83698c7a8f5b06186a5 to your computer and use it in GitHub Desktop.
Save Jibbarth/8b153ed3b1ffc83698c7a8f5b06186a5 to your computer and use it in GitHub Desktop.
Exception normalizer : Allow to have message of exception
<?php
declare(strict_types=1);
namespace App\Normalizer;
use Symfony\Component\ErrorHandler\Exception\FlattenException;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
/**
* Normalizer that allow to display Exception message only if Exception is an HttpExceptionInterface.
*/
final class HttpProblemNormalizer implements NormalizerInterface, NormalizerAwareInterface
{
use NormalizerAwareTrait;
private const ALREADY_CALLED = 'HTTP_PROBLEM_ALREADY_CALLED';
/**
* {@inheritdoc}
*/
public function normalize(mixed $object, string $format = null, array $context = [])
{
$context[self::ALREADY_CALLED] = true;
$data = $this->normalizer->normalize($object, $format, $context);
// Force to use exception message in detail instead of status text
$data['detail'] = $object->getMessage();
return $data;
}
public function supportsNormalization($data, string $format = null, array $context = []): bool
{
// avoid recursion: only call once per object
if (isset($context[self::ALREADY_CALLED])) {
return false;
}
if (!$data instanceof FlattenException) {
return false;
}
$implements = class_implements($data->getClass());
return \array_key_exists(HttpExceptionInterface::class, $implements);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment