title: Catch Doctrine exception on Controller
body: <p>I'm using Symfony 4 with Doctrine and am handling an entity which will be persisted.</p>
  
  <p>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.</p>
  
  <p>As of now my code looks like this</p>
  
  <pre><code>$user-&gt;setUsername($username)
      -&gt;setEmail($email)
      -&gt;setPassword($password);
  
      $em-&gt;persist($user);
      $em-&gt;flush();
  
  return $this-&gt;json(['msg'=&gt;'some message', 201);
  </code></pre>
  
  <p>I would like to be able to decide what to send in the Response in case there are errors.</p>