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

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


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.phpnamespace 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"}}


I've landed on this thread a number of times over the last few days. For anyone else in my situation where you are using V2 of the bundle, you may find the following resource on upgrading FOSRestBundle useful.

It covers the use of serializer in place of ExceptionWrapperHandlerInterface.

https://github.com/FriendsOfSymfony/FOSRestBundle/blob/master/UPGRADING-2.0.md

  • The exception_wrapper_handler config option was removed. Usenormalizers instead.

Before:

config.yml

fos_rest:   view:       exception_wrapper_handler: AppBundle\ExceptionWrapperHandler

Handler

namespace AppBundle;class ExceptionWrapperHandler implements ExceptionWrapperHandlerInterface{   public function wrap($data)   {       return new ExceptionWrapper(array('status_code' => 'foo'));   }}

After (if you use the Symfony serializer):

services.yml

services:   app_bundle.exception_normalizer:       class: AppBundle\Normalizer\ExceptionNormalizer       tags:           - { name: serializer.normalizer }

normalizer

namespace AppBundle\Normalizer;use Symfony\Component\Serializer\Normalizer\NormalizerInterface;class ExceptionNormalizer implements NormalizerInterface{   public function normalize($object, $format = null, array $context = array())   {       return array('status_code' => 'foo');   }   public function supportsNormalization($data, $format = null)   {       return $data instanceof \My\Exception;   }}