1

我在我的 Symfony 2.3 项目中使用 FOSRestBundle。

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

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

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

我有多个bundle,但只有一个是RestBundle,所以其他的bundle需要正常设置。

4

2 回答 2

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 }

如何创建事件监听器

于 2013-03-13T11:49:40.947 回答
0

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

# app/config/config.yml
fos_rest:
    format_listener:
        rules:
            - { path: '^/api/', priorities: ['json', 'xml'] }
            - { path: '^/', stop: true }
于 2020-12-08T00:28:14.253 回答