Spring3 @ExceptionHandler for ServletRequestBindingException

前端 未结 4 1439
醉话见心
醉话见心 2020-12-11 08:10

I am using a Default AnnotationMethodHandlerAdapter which I believe should enable support for @ExceptionHandler. Unluckily, a ServletRequestBindingException is thrown if a c

4条回答
  •  渐次进展
    2020-12-11 08:50

    This issue is fixed in Spring 3.2. You can create a global exception handler class with the @ControllerAdvice annotation. Then in that class add an @ExceptionHandler method to handle the ServletRequestBindingException and return a custom response body. Example:

    @ControllerAdvice
    public class GlobalExceptionHandler {
      @ExceptionHandler(ServletRequestBindingException.class)
      public ResponseEntity handleServletRequestBindingException(ServletRequestBindingException ex)   {
          return new ResponseEntity("MISSING REQUIRED HEADER",HttpStatus.PRECONDITION_REQUIRED);
      }
    }
    

    For more information check the spring mvc docs: 17.11 Handling exceptions

提交回复
热议问题