title: Symfony 3 API REST - Try Catch Exceptions to JSON response format
body: <p>I create the api rest server with Symfony and these bundles FosRestBundle, jms/serializer-bundle, lexik/jwt-authentication-bundle.</p>
  
  <p>How can I send a clean json response format like this :</p>
  
  <pre><code>Missing field "NotNullConstraintViolationException"
      {'status':'error','message':"Column 'name' cannot be null"}
  or
      {'status':'error','message':"Column 'email' cannot be null"}
  Or Duplicate entry "UniqueConstraintViolationException" :
      {'status':'error','message':"The email user1@gmail.com exists in database."}
  </code></pre>
  
  <p>Instead of system message:</p>
  
  <pre><code>UniqueConstraintViolationException in AbstractMySQLDriver.php line 66: An exception occurred while executing 'INSERT INTO user (email, name, role, password, is_active) VALUES (?, ?, ?, ?, ?)' with params ["user1@gmail.com", "etienne", "ROLE_USER", "$2y$13$tYW8AKQeDYYWvhmsQyfeme5VJqPsll\/7kck6EfI5v.wYmkaq1xynS", 1]: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'user1@gmail.com' for key 'UNIQ_8D93D649E7927C74'
  </code></pre>
  
  <p>Return a clean json reponse with the name mandatory or missed field.</p>
  
  <p>Here my controller:</p>
  
  <pre><code>    &lt;?php
  
  namespace AppBundle\Controller;
  
  use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
  use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
  use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  use Symfony\Component\HttpFoundation\Request;
  use Symfony\Component\HttpFoundation\Response;
  use AppBundle\Entity\User;
  use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
  use Symfony\Component\Debug\ExceptionHandler;
  use Symfony\Component\Debug\ErrorHandler;
  use Symfony\Component\HttpFoundation\JsonResponse;
  
  use FOS\RestBundle\Controller\Annotations as Rest; // alias pour toutes les annotations
  
  class DefaultController extends Controller
  {
  
  
   /**
   * @Rest\View()
   * @Rest\Post("/register")
   */
  public function registerAction(Request $request)
  {
      //catch all errors and convert them to exceptions
      ErrorHandler::register();
  
      $em = $this-&gt;get('doctrine')-&gt;getManager();
      $encoder = $this-&gt;container-&gt;get('security.password_encoder');
  
      $username = $request-&gt;request-&gt;get('email'); 
      $password = $request-&gt;request-&gt;get('password');
      $name = $request-&gt;request-&gt;get('name');
  
      $user = new User($username);
  
      $user-&gt;setPassword($encoder-&gt;encodePassword($user, $password));
      $user-&gt;setName($name);
      $user-&gt;setRole('ROLE_USER');
      try {
          $em-&gt;persist($user);
          $em-&gt;flush($user);
      }
      catch (NotNullConstraintViolationException $e) {
          // Found the name of missed field
              return new JsonResponse();
      } 
      catch (UniqueConstraintViolationException $e) {
          // Found the name of duplicate field
              return new JsonResponse();
      } 
      catch ( \Exception $e ) {
  
          //for debugging you can do like this
          $handler = new ExceptionHandler();
          $handler-&gt;handle( $e );
          return new JsonResponse(
              array(
                  'status' =&gt; 'errorException', 
                  'message' =&gt; $e-&gt;getMessage()
              )
          );
      }
  
      return new Response(sprintf('User %s successfully created', $user-&gt;getUsername()));
  }
  }
  </code></pre>
  
  <p>thanks</p>