Skip to content

Support collect denormalization type errors in serializer #4793

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
benblub opened this issue Jun 15, 2022 · 0 comments
Closed

Support collect denormalization type errors in serializer #4793

benblub opened this issue Jun 15, 2022 · 0 comments

Comments

@benblub
Copy link
Contributor

benblub commented Jun 15, 2022

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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants