生产环境下的FOSRestBundle异常消息配置

7
我遇到了与FOSRestBundle(版本0.13.*)相关的问题。
我有一些REST API会抛出一些异常,这似乎并不太寻常。但是,尽管我按照我在此处找到的文档进行了特定的配置,以便即使在生产环境中也可以在响应中格式化异常消息(文档如下:https://github.com/FriendsOfSymfony/FOSRestBundle/blob/master/Resources/doc/4-exception-controller-support.md),JSON响应仍然是空的。
以下是示例:
http://host/app_dev.php/api/postcode/search?postcode=  

导致结果:

HTTP 400: {"status":"error","status_code":400,"status_text":"Bad Request","current_content":"","message":"You must provide a postcode"}

但是
http://host/api/postcode/search?postcode=

导致结果为:

HTTP 400: []

我的API控制器是这样的:
/**
 * Search post codes
 *
 * @param Request   $request   Request
 * @param Promotion $promotion Promotion
 *
 * @Rest\View()
 *
 * @throws BadRequestHttpException
 * @return array
 */
public function searchAction(Request $request, Promotion $promotion)
{
    // Get post code
    $postCode = $request->query->get('postcode');
    if (!$postCode) {
        throw new BadRequestHttpException('You must provide a postcode');
    }

    // SOME LOGIC HERE TO GET DATA

    return $data;
}

而fos_rest的配置看起来像这样:

fos_rest:
    routing_loader:
        default_format: json
    view:
        mime_types:
            json: ['application/json; charset=UTF-8']
        formats:
            json: true
        view_response_listener: force
    format_listener: false
    access_denied_listener:
        json: true
    body_listener: true
    exception:
        messages:
            Symfony\Component\HttpKernel\Exception\BadRequestHttpException: true

据我所知,fos_rest.exception.messages配置数组应列出我希望即使在生产环境中也要序列化错误消息的异常。正如您在控制器代码中看到的那样,此响应包含将显示给客户端的翻译错误消息。为什么会忽略此配置?
我可以确定即使在生产环境中,该配置也已正确加载,因为如果我在配置中拼写类名错误,它会失败并出现“无法加载类”异常。
我错过了什么?非常感谢您能给我的任何提示...

嗨,如果您能标记我的答案是否正确,我会非常感激:D 谢谢 - timhc22
2个回答

7

我遇到了类似的问题,实际上你的问题帮助我解决了它!虽然有点晚了,但我发现清除 prod 缓存对我来说很有帮助。

以下是我的设置:

fos_rest:
    param_fetcher_listener: true
    body_listener:
        array_normalizer: fos_rest.normalizer.camel_keys
    format_listener: true
    view:
        view_response_listener: 'force'
        formats:
            json: true
        templating_formats:
            html: true
        force_redirects:
            html: true
        failed_validation: HTTP_BAD_REQUEST
        default_engine: twig
    routing_loader:
        default_format: json
    serializer:
        serialize_null: true
    access_denied_listener:
        json: true
    exception:
        enabled: true
        messages:
            Symfony\Component\HttpKernel\Exception\BadRequestHttpException: true

我想知道是否总是需要在配置文件的codesmessages部分明确添加异常,除非你使用HttpException:

throw new HttpException(400, "New comment is not valid.");

谢谢!exception.messages正是我在寻找的。 - Aistis

0

我没有尝试过这个,但是看起来你忘记了这一行:

 exception:
    codes:
      'Symfony\Component\Routing\Exception\ResourceNotFoundException': 404

试一下。

你有提到这个吗:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接