Exception handler in Spring MVC

前端 未结 3 1270
暖寄归人
暖寄归人 2020-12-13 07:12

I want to create an exception handler which will intercept all controllers in my project. Is that possible to do? Looks like I have to put a handler method in each controlle

3条回答
  •  盖世英雄少女心
    2020-12-13 07:43

    Since Spring 3.2 you can use @ControllerAdvice annotation. You can declare an @ExceptionHandler method within an @ControllerAdvice class in which case it handles exceptions from @RequestMapping methods from all controllers.

    @ControllerAdvice
    public class MyGlobalExceptionHandler {
    
        @ExceptionHandler(value=IOException.class)
        public @ResponseBody String iOExceptionHandler(Exception ex){
            //
            //
        }
    
        // other exception handler methods
        // ...
    
    }
    

提交回复
热议问题