设置FOSRestBundle异常_format

时间:2013-03-13 11:35:32

标签: json exception symfony fosrestbundle

我在Symfony 2.3项目中使用FOSRestBundle。

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

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

默认返回是HTML格式,但是 是否可以将_format = json设置为返回异常?

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

在向FosRest控制器发出请求时,捕获symfony异常并返回json的最简单方法是:

# app/config/config.yml
fos_rest:
    format_listener:
        rules:
            - { path: '^/api/', priorities: ['json', 'xml'] }
            - { path: '^/', stop: true }