Spring 3 - Create ExceptionHandler for NoSuchRequestHandlingMethodException

前端 未结 3 772
一整个雨季
一整个雨季 2021-01-31 09:18

Using Spring 3, I like to create an exception handler using the ExceptionHandler annotation that will handle \"no page found (404)\" requests.

3条回答
  •  Happy的楠姐
    2021-01-31 09:57

    In Spring 3.2 you can use @ContollerAdvice to have an ExceptionHandler for all your Controllers like this:

    @ControllerAdvice
    public class GeneralHandler {
    
       @ExceptionHandler
       public ModelAndView handleException (NoSuchRequestHandlingMethodException ex) {
            ModelAndView mav = new ModelAndView();
            ...
            return mav;
       }
    }
    

    You can even add more annotations to return serialized json

    @ExceptionHandler
        @ResponseBody
        @ResponseStatus(HttpStatus.BAD_REQUEST)
        public RestError resolveBindingException ( MethodArgumentNotValidException methodArgumentNotValidException, Locale locale )
        {
            BindingResult bindingResult = methodArgumentNotValidException.getBindingResult();
            return getRestError(bindingResult, locale);
        }
    

提交回复
热议问题