I have a user entity which have some unique fields.
The code bellow shows you how I defined it.
/**
* @UniqueEntity(fields={"login"}, message="UNIQUE ERROR MESSAGE")
*/
......
/**
* @var string
*
* @ORM\Column(name="login", type="string", length=255, unique=true)
*/
private $login;
Developping an API, I would like to be able to send the right error status with the right error message.
When I insert a duplicate entry in the database, I would like to get the message and an exeption relative to the fact it is a duplicate. Instead I get a 500 error with the SQL Message.
{
"error": {
"code": 500,
"message": "Internal Server Error",
"exception": [
{
"message": "An exception occurred while executing 'INSERT INTO .... \n\nSQLSTATE[23505]: Unique violation: 7 ERROR: duplicate key value violates unique constraint \"uniq_1d1c63b3aa08cb10\"\nDETAIL: Key (login)=(bast) already exists.",
"class": "Doctrine\\DBAL\\DBALException",
"trace": [
Here is where I get the 500.
$test = new Utilisateur();
$test->setLogin('test');
$manager = $this->getDoctrine()->getManager();
$manager->persist($test);
$manager->flush();
How can I retrieve the message "UNIQUE ERROR MESSAGE" ?
The Symfony validator service can be used directly to validate any object for which validation constraints are defined. For example in a controller:
To perform validation within a service you can pass the validator service into your service.