FOSRestBundle: show my custom exception message

烈酒焚心 提交于 2020-01-15 08:16:08

问题


I'm trying to add a custom control of exceptions in FOSRestBundle but it seems to ignore my custom messages (the status code of the response is ok).

I have:

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

But get this json response:

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

So I don't find the way to show my custom message


回答1:


You could also throw you own exception using the following configuration:

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

Provide a custom message in your own exception class and it should work as expected.




回答2:


On the View Layer documentation: 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



回答3:


To display your custom exception message (simply into app/config/config.yml):

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


来源:https://stackoverflow.com/questions/24979499/fosrestbundle-show-my-custom-exception-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!