Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set http code for Symfony constraint validation failure

Shortly: how can you set a specific http error code, instead of a generic 500, when a constraint fails on entity save?

Details

I'm using Symfony custom constraint @UniqueEntity (http://symfony.com/doc/current/reference/constraints/UniqueEntity.html) to assert that some data is not duplicated when saving an entity.

If this constraint check results in a violation, I get a 500 http code, while others may be more appropriate, e.g. 409 - Conflict (https://httpstatuses.com/409).

I can't seem to find any documentation on how to override the validation response.

Thank you in advance for any suggestion.

like image 415
Francesco Abeni Avatar asked Feb 16 '26 06:02

Francesco Abeni


2 Answers

Maybe you could create a Listener to the event : kernel.exception

And then you will have something like :

<?php

public function onKernelException(GetResponseForExceptionEvent $event)
{
      $e = $event->getException();

      if ($e instanceof NameOfTheException) {
            // logic here

            return (new Response())
                  ->setStatusCode(409)
            ;
      }
}
like image 73
Adrien G Avatar answered Feb 18 '26 18:02

Adrien G


Just catch exception in controller:

public function saveAction()
{
    try {
       $entity = new Entity('duplicate name');

       $this->entityManager->persist($entity);
       $this->entityManager->flush();

       return new Response();
    } catch(UniqueConstraintViolationException $e) {
       return new Response('Entity with same name already exists', Response::HTTP_CONFLICT);
    } catch (\Exception $e) {
       return new Response('Internal error', Response::HTTP_INTERNAL_SERVER_ERROR);
    }
}
like image 38
d.garanzha Avatar answered Feb 18 '26 20:02

d.garanzha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!