Silex: How to not redirect Access Denied Responses for Ajax Requests

While it is useful to redirect users to the login form when making a request that needs authentication, it is bad for webservices or Ajax driven applications. This little snippet prevents the redirect and sends a 403 response for Ajax Requests:

$app['dispatcher']->addListener("kernel.exception", function(Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event) {
  if ($event->getException()->getCode() == '403')
    $request = $event->getRequest();
    if ($request->isXmlHttpRequest()) {
      $event->setResponse(new Response("Access Denied", 403));