Symfony2,FOSRestBundle - 捕获异常

时间:2015-11-30 15:50:38

标签: php angularjs symfony

我有Symfony应用程序,我使用FOSRestBundle和AngularJS。我的Symfony应用程序没有任何意见。

我想在AngularJS消息中显示使用ngToast模块从服务器收到的信息。

如果我创建或更新它,很容易显示。但是如果服务器抛出一些异常?例如,Angular客户端尝试获取具有错误ID的项目,或者此用户没有访问权来执行此操作?在这种情况下,服务器将抛出异常,但我想显示相应的消息。

symfony可以捕获此异常,例如将其转换为Response对象吗? 例如 - 如果我有无权访问异常,symfony应该抓住它并做出类似这样的事情:

return new Response(400, "You don't have permission to acces this route");

和Angular会得到:

{
    "code": 400,
    "message": "You don't have permission to acces this route"
}

有可能吗?我该怎么办?也许我应该以其他方式去做。

2 个答案:

答案 0 :(得分:4)

我建议采用更多的FOSRestBundle方法,即配置例外,是否应该显示消息:

fos_rest:
  exception:
    enabled: true
    codes:
      'Symfony\Component\Routing\Exception\ResourceNotFoundException': HTTP_FORBIDDEN
    messages:
      'Symfony\Component\Routing\Exception\ResourceNotFoundException': true

假设您对某个操作有自定义的AccessDeniedException,您可以创建该异常,然后将其置于配置中。

<?php
class YouCantSummonUndeadsException extends \LogicException
{
}

无论你扔到哪里:

<?php
throw new YouCantSummonUndeadsException('Denied!');

您可以配置它:

    codes:
      'My\Custom\YouCantSummonUndeadsException': HTTP_FORBIDDEN
    messages:
      'My\Custom\YouCantSummonUndeadsException': true

得到如下结果:

{
    "code": 403,
    "message": "Denied!"
}

我希望这更清楚!

答案 1 :(得分:2)

是的,当然这是可能的。我建议你实现一个简单的Exception监听器。并使所有异常类扩展BaseException或实现BaseException,因此您将知道哪些异常来自“您的”代码。

class ExceptionListener
{
    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        // You get the exception object from the received event
        $exception = $event->getException();

        // Do your stuff to create the response, for example response status code can be exception code, and exception message can be in the body or serialized in json/xml.

        $event->setResponse($response);

        return;
    }

}

在容器中注册:

<service id="your_app.listener.exception" class="App\ExceptionListener">
    <tag name="kernel.event_listener" event="kernel.exception" method="onKernelException" />
</service>
相关问题