我想在Symfony3上创建一个自定义Exception,它返回一个JSON响应,以便之后能够在JavaScript中处理它。
有人知道是否可能以及如何做到这一点?
答案 0 :(得分:1)
创建一个新的异常处理程序类,如下所示:
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);
}
}
不要忘记在 app / config / services.yml 中注册新服务:
app.exception_subscriber:
class: AppBundle\Subscriber\ExceptionSubscriber
tags:
- { name: kernel.event_subscriber }