2013-03-13 81 views
1

我在我的Symfony 2.3项目中使用FOSRestBundle。设置FOSRestBundle异常_format

我无法为响应异常设置_format。 在我config.yml我:

twig: 
    exception_controller: 'FOS\RestBundle\Controller\ExceptionController::showAction' 

默认返回的是HTML格式,但 是有可能设置_format = json返回例外?

我有多个捆绑包,但只有一个是RestBundle,所以其他捆绑包需要以正常方式设置。

+0

您是否在更改config.yml后清除了缓存? – Sethunath 2013-03-13 13:50:10

+0

我总是在变化之后做到这一点。 – mrzepinski 2013-03-13 14:00:45

回答

2

您可以手动编写你的路由,并设置_format有这样的:

acme_demo.api.user: 
    type: rest 
    pattern: /user/{username_canonical}.{_format} 
    defaults: { _controller: 'AcmeDemoBundle:User:getUser', username_canonical: null, _format: json } 
    requirements: 
     _method: GET 

编辑:或者你可以写自己的异常处理程序,并与任何你需要做的例外做到:

// src/Acme/DemoBundle/EventListener/AcmeExceptionListener.php 
namespace Acme\DemoBundle\EventListener; 

use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent; 
use Symfony\Component\HttpFoundation\JsonResponse; 
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface; 

class AcmeExceptionListener 
{ 
    public function onKernelException(GetResponseForExceptionEvent $event) 
    { 
     // do whatever tests you need - in this example I filter by path prefix 
     $path = $event->getRequest()->getRequestUri(); 
     if (strpos($path, '/api/') === 0) { 
      return; 
     } 

     $exception = $event->getException(); 
     $response = new JsonResponse($exception, 500); 

     // HttpExceptionInterface is a special type of exception that 
     // holds status code and header details 
     if ($exception instanceof HttpExceptionInterface) { 
      $response->setStatusCode($exception->getStatusCode()); 
      $response->headers->replace($exception->getHeaders()); 
     } 

     // Send the modified response object to the event 
     $event->setResponse($response); 
    } 
} 

并将其注册为一个监听器:

# app/config/config.yml 
services: 
    kernel.listener.your_listener_name: 
     class: Acme\DemoBundle\EventListener\AcmeExceptionListener 
     tags: 
      - { name: kernel.event_listener, event: kernel.exception, method: onKernelException } 

How to create an Event Listener

+0

在我的路由配置中,对于所有Restful方法,我有'_format:json'。问题是,例外的默认格式是'html',我不知道如何改变它。 – mrzepinski 2013-03-13 11:58:04

+0

我已经添加了自定义异常处理教程的链接。在侦听器中设置Response(如示例所示)使得Symfony可以返回它。 – 2013-03-13 21:14:39

+0

谢谢。这可能会有所帮助,但如何将此类例外用于RestBundle服务,其余部分保持不变? – mrzepinski 2013-03-14 06:13:23