FOSRestBundle:显示我的自定义异常消息

时间:2014-07-27 09:08:24

标签: php symfony exception fosrestbundle

我正在尝试在FOSRestBundle中添加自定义异常控件,但它似乎忽略了我的自定义消息(响应的状态代码正常)。

我有:

throw new HttpException(404, "User {$id} not found");

但是得到这个json的回应:

{
  "error": {
    "code": 404,
    "message": "Not Found"
  }
}

所以我找不到显示自定义消息的方法

4 个答案:

答案 0 :(得分:4)

View Layer documentationIf you don't like the default exception structure, you can provide your own implementation.

class ExceptionWrapperHandler implements ExceptionWrapperHandlerInterface
{
    /**
     * @param array $data
     *
     * @return array
     */
    public function wrap($data)
    {
        // we get the original exception
        $exception = $data['exception'];

        // some operations
        // ...

        // return the array
        return array(
            'code'    => $code,
            'message' => $message,
            'value'   => $value
        );
    }
}


// config.yml
fos_rest:
    view:
        exception_wrapper_handler: Namespace\To\ExceptionWrapperHandler

答案 1 :(得分:3)

您还可以使用以下配置抛出自己的异常:

fos_rest:
    exception:
        codes:
            'My\Custom\NotFound\Exception404': 404
        messages:
            'My\Custom\NotFound\Exception404': true

在您自己的异常类中提供自定义消息,它应该按预期工作。

答案 2 :(得分:1)

显示自定义异常消息(只需显示在app / config / config.yml中):

fos_rest:
    exception:
         messages:
            Symfony\Component\HttpKernel\Exception\HttpException: true

答案 3 :(得分:0)

另一种简单的解决方案是像这样在fos_rest配置中设置debug标志:

fos_rest:
    // ...
    exception:
        // ...
        debug: true

这将显示所有例外的实际例外消息。显然,这可能会带来安全风险,因此请谨慎使用。