1

Symfony 2.3 プロジェクトで FOSRestBundle を使用しています。

応答の例外に _format を設定できません。私の config.yml には次のものがあります。

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

デフォルトのリターンはHTML形式ですが、_format = json例外を返すように設定することはできますか?

複数のバンドルがありますが、RestBundle は 1 つだけなので、他のバンドルは通常の方法で設定する必要があります。

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 に答える