Json 设置FOSRestBundle异常\u格式
我在Symfony 2.3项目中使用FOSRestBundle 我无法为响应异常设置_格式。 在my config.yml中,我有:Json 设置FOSRestBundle异常\u格式,json,exception,symfony,fosrestbundle,Json,Exception,Symfony,Fosrestbundle,我在Symfony 2.3项目中使用FOSRestBundle 我无法为响应异常设置_格式。 在my config.yml中,我有: twig: exception_controller: 'FOS\RestBundle\Controller\ExceptionController::showAction' 默认返回为HTML格式,但 是否可以将\u format=json设置为返回异常 我有多个bundle,但只有一个是RestBundle,因此其他bundle需要以正常方式设置。您
twig:
exception_controller: 'FOS\RestBundle\Controller\ExceptionController::showAction'
默认返回为HTML格式,但
是否可以将\u format=json
设置为返回异常
我有多个bundle,但只有一个是RestBundle,因此其他bundle需要以正常方式设置。您可以手动编写路由并在那里设置
\u格式,如下所示:
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 }
当向FosRest控制器发出请求时,捕获symfony异常并返回json的最简单方法如下:
#app/config/config.yml
fos_休息:
格式\u侦听器:
规则:
-{path:'^/api/',优先级:['json','xml']}
-{path:'^/',stop:true}
在我的路由配置中,对于我拥有的所有Restful方法\u格式:json
。问题是,异常的默认格式是html
,我不知道如何更改它。我添加了一个指向自定义异常处理教程的链接。在侦听器中设置响应(如示例所示)会使Symfony返回响应。谢谢。这可能会有帮助,但是如何将此类异常用于RestBundle服务,而其余的保持不变?在自定义内核中保持控制器不变。如果要处理该异常,请检查异常事件侦听器(例如,检查某些路由匹配或路径前缀)。如果要处理异常,请处理它并设置响应,否则不执行任何操作,异常将按通常方式处理。@tomas.pecserke,strps()
至少需要两个参数。更改config.yml后是否清除缓存?我总是在更改后执行此操作。