core icon indicating copy to clipboard operation
core copied to clipboard

Support collect denormalization type errors in serializer

Open benblub opened this issue 3 years ago • 0 comments

Description
For Resources collect denormalization type errors in serializer and return them in http response as constraint violations. use Symfony 5.4 serializer's feature https://symfony.com/blog/new-in-symfony-5-4-serializer-improvements#collect-denormalization-type-errors

Example
When trying to deserialize that data you'll see a 500 error because the type of property1 is string and you're passing a null value. In Symfony 5.4 we've improved this behavior thanks to the new COLLECT_DENORMALIZATION_ERRORS option.

If you pass that option, the PHP exception will include the detailed list of errors. Then you can process it like in the following example that handles some API:

#[Route('/api', methods:['POST'])]
public function apiPost(SerializerInterface $serializer, Request $request): Response
{
    try {
       $dto = $serializer->deserialize($request->getContent(), MyDto::class, 'json', [
            DenormalizerInterface::COLLECT_DENORMALIZATION_ERRORS => true,
        ]);
    } catch (PartialDenormalizationException $e) {
        $violations = new ConstraintViolationList();
        /** @var NotNormalizableValueException */
        foreach ($e->getErrors() as $exception) {
            $message = sprintf('The type must be one of "%s" ("%s" given).', implode(', ', $exception->getExpectedTypes()), $exception->getCurrentType());
            $parameters = [];
            if ($exception->canUseMessageForUser()) {
                $parameters['hint'] = $exception->getMessage();
            }
            $violations->add(new ConstraintViolation($message, '', $parameters, null, $exception->getPath(), null));
        };

        return $this->json($violations, 400);
    }

    return $this->json($dto);
}

benblub avatar Jun 15 '22 07:06 benblub