title: How can I catch errors and exceptions in Symfony2/Silex?
body: <p>I'd like to catch both errors and exceptions in my Silex app to wrap them in a custom JSON response that will always be returned to clients. I've found three basic methods:</p>
  
  <pre><code>$app-&gt;error()
  Symfony\Component\Debug\ErrorHandler::register();
  Symfony\Component\Debug\ExceptionHandler::register();
  </code></pre>
  
  <p>While I'm able to catch controller exceptions using <code>error()</code> I'm failing with php errors- they always end up in xdebug. 
  I'm also failing to understand how <code>error()</code> and <code>ExceptionHandler::register()</code> interact with each other- do I need both? How can I make sure my <code>error()</code> response is JSON?</p>
  
  <p>I've got the following example code right now:</p>
  
  <pre><code>use Silex\Application;
  use Symfony\Component\HttpFoundation\Request;
  use Symfony\Component\HttpFoundation\Response;
  
  class Router extends Silex\Application
  {
      function __construct() {
          parent::__construct();
  
          // routes
          $this-&gt;match('/{context}', array($this, 'handler'));
  
          // error handler
          $this-&gt;error(function(\Exception $e, $code) {
              return $this-&gt;json(array("error" =&gt; $e-&gt;getMessage()), $code);
          });
      }
  
      function handler(Request $request, $context) {
          // throw new \Exception('test'); // exception- this is caught
          $t = new Test(); // error- this is not caught
  
          return 'DONE';
      }
  }
  
  Symfony\Component\Debug\ErrorHandler::register();
  
  $app = new Router();
  $app-&gt;run();
  </code></pre>