-->

Custom exception with fosrest bundle in symfony2

2019-07-23 21:59发布

问题:

Hi I am trying to add custom exception but it is not working

now my response is like:(also the breakdown debuger is not trigger that class)

{
  "error": {
    "code": 500,
    "message": "Required Parameter Missing"
  }
}

this is the default exception of fos rest I added new class that wrapp the exception

  class ExceptionWrapperHandler implements ExceptionWrapperHandlerInterface {
public function wrap($data)
{
    $exception = $data['exception'];

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

}

}

my config file:

fos_rest:
    param_fetcher_listener: true
    body_listener: true
    format_listener: true
    routing_loader:
           default_format: json
    view:
        view_response_listener: force
        formats:
            json: true
            xml: true
        templating_formats:
            html: false
#        exception_wrapper_handler: CLASS path
    exception:
        enabled: true
    service:
        exception_handler: appname.exception_handler 
        serializer: jms_serializer.serializer
    serializer:
        serialize_null: true

回答1:

You need to add your Exception class to the exception.messages array in your fos_rest config in your config.yml for it to show your custom message

fos_rest:
    exception:
        enabled: true
        messages:
            'AppBundle\ExpeptionHandler\ ExceptionWrapperHandler': true