如何在symfony2路由中添加特定异常

时间:2015-12-28 08:42:19

标签: symfony exception routing routes conditional-statements

如何在symfony2路由中添加特定异常。

contact:
    path:     /contact
    defaults: { _controller: AcmeDemoBundle:Main:contact }
    condition: "(context.getMethod() in ['GET', 'HEAD'] and request.headers.get('User-Agent') matches '/firefox/i') ?: [exception]"

2 个答案:

答案 0 :(得分:0)

是否应该抛出异常不是路由决定。这是一个合乎逻辑的决定,因此应放在您的控制器中。

从路线中移除condition并将其设置在您的控制器中:

public function contactAction(Request $request)
{
    if (
        !in_array(array('GET', 'HEAD'), $request->getMethod())
        || 1 !== preg_match('/firefox/i', $request->headers->get('User-Agent'))
    ) {
        throw new BadRequestHttpException('Bad request');
    }
}

答案 1 :(得分:0)

您可以使用ExceptionResponseListener根据您的需要发送自定义响应。

// src/Acme/AppBundle/EventListener/ExceptionResponseListener.php
<?php

namespace Acme\AppBundle\EventListener;

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

class ExceptionResponseListener
{
    /**
     * @param GetResponseForExceptionEvent $event
     */
    public function onKernelResponse(GetResponseForExceptionEvent $event)
    {
        $request = $event->getRequest();
        $routeName = $request->get('_route');
        // Check if it's the good route (or namespace ..)
        if ('your_route' !== $routeName) {
            return;
        }
        $exception =  $event->getException();
        $statusCode = 500;
        $message = $exception->getMessage();

        // Choose the Exception you intercept.
        if ($exception instanceof NotFoundHttpException) {
            $statusCode = $exception->getStatusCode();
            $message = $exception->getMessage();
        }

        // Create your own response
        $content = ['error' => $message];
        $response = new JsonResponse($content, $statusCode);

        // Update the event response
        $event->setResponse($response);
    }
}

然后,将其注册为服务:

parameters:
    acme.kernel.listener.exception_listener.class:
        Acme\AppBundle\EventListener\ExceptionResponseListener
services:
    acme.kernel.listener.exception_listener:
        class: %acme.kernel.listener.exception_listener.class%
        tags:
            - {name: kernel.event_listener, event: kernel.exception, method: onKernelResponse}

像这样你可以发送自己的。 这里的文档:http://symfony.com/doc/current/cookbook/event_dispatcher/event_listener.html