2

I'm using Symfony 4 with Doctrine and am handling an entity which will be persisted.

I would like to know how can I have a kind of try\catch handling when an exception occurs while persisting, so that I can send different errors accordingly.

As of now my code looks like this

$user->setUsername($username)
    ->setEmail($email)
    ->setPassword($password);

    $em->persist($user);
    $em->flush();

return $this->json(['msg'=>'some message', 201);

I would like to be able to decide what to send in the Response in case there are errors.

LuisF
  • 564
  • 1
  • 7
  • 18

1 Answers1

5

You can catch errors simply as follows, but you will have to check with the conditions.

try {
    $user->setUsername($username)
    ->setEmail($email)
    ->setPassword($password);

    $em->persist($user);
    $em->flush();
} 
catch(DBALException $e){
    $errorMessage = $e->getMessage();
}    
catch(\Exception $e){
    $errorMessage = $e->getMessage();
}
Deniz Aktürk
  • 362
  • 1
  • 9
  • what do you mean by check with the conditions? Also, the DBALException is any exception thrown by Doctrine? – LuisF Jun 03 '18 at 11:16
  • You need to check exceptions to customize error messages, I was talking about this. doctrine returns an exception with DBALException, if you do not return the exception here, you need to use the general exception. – Deniz Aktürk Jun 03 '18 at 18:41
  • The Doctrine\DBAL\DBALException and Doctrine\DBAL\Driver\DriverException have been renamed to Doctrine\DBAL\Exception and Doctrine\DBAL\Driver\Exception respectively. https://github.com/doctrine/dbal/releases – Danil Pyatnitsev Apr 13 '21 at 08:01
  • A good rule of thumb is that you should only catch exceptions that you can properly deal with yourself. If you cannot handle the exception completely then you should let it bubble up to someone who can. See https://stackoverflow.com/questions/21938/is-it-really-that-bad-to-catch-a-general-exception – Rubinum Jul 14 '22 at 07:03