FOSRestBundle: show my custom exception message

K. Weber picture K. Weber · Jul 27, 2014 · Viewed 9k times · Source

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

Answer

AlixB picture AlixB · Jul 28, 2014

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