symfony覆盖响应

时间:2018-05-03 13:24:14

标签: symfony

我正在使用symfony 2.8网络应用程序,在这个应用程序中我需要在ajax请求上返回403 json响应,即使用户没有登录而是重定向。为了解决这个问题,我确实使用了一个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();
    }
  }
}

并设置高于默认值ExceptionListener的优先级它工作正常但是当我发出AJAX请求时,我得到了预期的内容,但没有获得statusCode(而是500)

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

所以我的问题......我做错了什么或者我错过了什么......谢谢。

1 个答案:

答案 0 :(得分:1)

经过长时间的调试后,我发现了错误。我傻了......

我的代码是

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

代替

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

同样通过设置对事件的响应,它会停止传播。

相关问题