How do you customize exception format with FOSRestBundle and Symfony 2?

Slava Fomin II picture Slava Fomin II · Jun 11, 2015 · Viewed 10.6k times · Source

I'm using FOSRestBundle with Symfony 2 to implement a REST API in JSON format.

I want all API exceptions to be returned in a specific JSON format like this:

{
    "success": false,
    "exception": {
        "exceptionClass": "SomeNastyException",
        "message": "A nasty exception occurred"
    }
}

How do I do this?

I've tried to fiddle with ExceptionController, but it's logic seems too complicated to be easily overloaded.

Answer

Artem  Zhuravlev picture Artem Zhuravlev · Jun 11, 2015

Note: This works only for FOSResBundle < 2.0. For FOSResBundle >= 2.0 please use Exception Normalizers, see examples.

You can write custom exception wrapper handler like in docs. In your case:

<?php
//AppBundle\Handler\MyExceptionWrapperHandler.php
namespace AppBundle\Handler;

use FOS\RestBundle\Util\ExceptionWrapper;
use FOS\RestBundle\View\ExceptionWrapperHandlerInterface;

class MyExceptionWrapperHandler implements ExceptionWrapperHandlerInterface {

    public function wrap($data)
    {
        /** @var \Symfony\Component\Debug\Exception\FlattenException $exception */
        $exception = $data['exception'];

        $newException = array(
            'success' => false,
            'exception' => array(
                'exceptionClass' => $exception->getClass(),
                'message' => $data['status_text']
            )
        );

        return $newException;
    }
}

app/config/config.yml

fos_rest:
    routing_loader:
        default_format: json

    view:
        view_response_listener: force
        exception_wrapper_handler: AppBundle\Handler\MyExceptionWrapperHandler

    exception:
          enabled: true

Response example:

{"success":false,"exception":{"exceptionClass":"Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException","message":"Not Found"}}