engel
engel

Reputation: 11

symfony overrides status code in response

I'm working on a symfony 2.8 web app, in this app I need to return a 403 json response on ajax request even if the user is not logged in instead a redirection. In order to solve that I did use a Listener:

class AccessDeniedListener {

public function onAccessDeniedException(GetResponseForExceptionEvent $event) {
    if ($event->getException()->getCode() === 403
            && $event->getRequest()->isXmlHttpRequest()) {
        $event->setResponse(new JsonResponse(['foo' => 'bar']), 403);
        $event->stopPropagation();
    }
  }
}

and set a priority higher than the default ExceptionListener it works fine but when I make an AJAX request I get the expected content but not the statusCode (500 instead)

$.get('http://localhost/web/app_dev.php/test').fail(function( jqXHR, textStatus ) {
  console.log(jqXHR.status); //returns 500
});

So my question... I'm doing anything wrong or I missing something... thanks.

Upvotes: 0

Views: 577

Answers (1)

engel
engel

Reputation: 11

After a long time debugging I find out the error. I fell silly..

My code was

$event->setResponse(new JsonResponse(['foo' => 'bar']), 403);

instead

$event->setResponse(new JsonResponse(['foo' => 'bar'], 403));

Also by setting a response to the event it stops the propagation.

Upvotes: 1

Related Questions