我使用 FOSRestBundle 将错误消息格式转换为 JSON 。
这是config.yml中的 fos_rest 和 twig 配置部分:
public function showAction(Request $request, $exception, DebugLoggerInterface $logger = null)
{
if (!$exception instanceof DebugFlattenException && !$exception instanceof HttpFlattenException) {
throw new \InvalidArgumentException(sprintf(
'ExceptionController::showAction can only accept some exceptions (%s, %s), "%s" given',
'Symfony\Component\HttpKernel\Exception\FlattenException',
'Symfony\Component\Debug\Exception\FlattenException',
get_class($exception)
));
}
try {
$format = $this->getFormat($request, $request->getRequestFormat());
} catch (\Exception $e) {
$format = null;
}
if (null === $format) {
$message = 'No matching accepted Response format could be determined, while handling: ';
$message .= $this->getExceptionMessage($exception);
return $this->createPlainResponse($message, Codes::HTTP_NOT_ACCEPTABLE, $exception->getHeaders());
}
$currentContent = $this->getAndCleanOutputBuffering($request);
$code = $this->getStatusCode($exception);
$viewHandler = $this->container->get('fos_rest.view_handler');
$parameters = $this->getParameters($viewHandler, $currentContent, $code, $exception, $logger, $format);
$showException = $request->attributes->get('showException', $this->container->get('kernel')->isDebug());
try {
if (!$viewHandler->isFormatTemplating($format)) {
$parameters = $this->createExceptionWrapper($parameters);
}
$view = View::create($parameters, $code, $exception->getHeaders());
$view->setFormat($format);
if ($viewHandler->isFormatTemplating($format)) {
$view->setTemplate($this->findTemplate($request, $format, $code, $showException));
}
$response = $viewHandler->handle($view);
} catch (\Exception $e) {
$message = 'An Exception was thrown while handling: ';
$message .= $this->getExceptionMessage($exception);
$response = $this->createPlainResponse($message, Codes::HTTP_INTERNAL_SERVER_ERROR, $exception->getHeaders());
}
return $response;
}
问题在于所有页面(即使状态代码= 200)都被转换,而且不仅在发生错误时(404,500,...)
已编辑: 我使用了FOSRestBundle的 ExceptionController 的默认 showAction :
{{1}}