显示我的自定义异常消息


FOSRestBundle: show my custom exception message

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

:

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

但是得到这个json响应:

{
  "error": {
    "code": 404,
    "message": "Not Found"
  }
}
所以我找不到显示自定义消息的方法

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

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

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

View Layer文档:If 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

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

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

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

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

这将显示所有异常的实际异常消息。显然,这可能存在安全风险,因此请谨慎使用。