2016-10-28 44 views
1

我想在Symfony3上创建一个自定义异常,该自定义异常返回一个JSON响应,以便之后能够在JavaScript中处理它。Symfony3自定义异常返回JSON响应

有人知道是否有可能以及如何去做?

+0

你可以简单地返回一个'新的响应(json_encode(...))'当然有适当的头文件。 – Andrew

+0

这的确是我目前所做的。但我真的希望能够在返回Json代码的简单页面和返回Json代码的异常之间的代码中发挥不同... – Fab

+0

您可以通过异常处理程序,标准json响应,异常冒泡类(异常处理类的花哨词),我敢肯定还有其他方法。 – Andrew

回答

0

创建一个新的异常处理程序类,像这样:

namespace AppBundle\Subscriber; 

use Symfony\Component\EventDispatcher\EventSubscriberInterface; 
use Symfony\Component\HttpFoundation\JsonResponse; 
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent; 

class ExceptionSubscriber implements EventSubscriberInterface 
{ 

    /* ... */ 

    public static function getSubscribedEvents() 
    { 
     return [ KernelEvents::EXCEPTION => 'onKernelException' ]; 
    } 

    public function onKernelException(GetResponseForExceptionEvent $event) 
    { 
     $customResponse = new JsonResponse(['error' => 'My custom error message']); 
     $event->setResponse($customResponse); 
    } 

} 

不要忘记在应用注册新的服务/配置/ services.yml

app.exception_subscriber: 
    class: AppBundle\Subscriber\ExceptionSubscriber 
    tags: 
     - { name: kernel.event_subscriber }