用@ExceptionHandler 來進行異常處理

有時候我們想統一處理一個Controller中拋出的異常怎麼搞呢?

直接在Controller裏面加上用@ExceptionHandler標註一個處理異常的方法像下面這樣子

@ExceptionHandler(MissingServletRequestParameterException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public void processMethod(MissingServletRequestParameterException ex,HttpServletRequest request ,HttpServletResponse response) throws IOException {
    System.out.println("拋異常了!"+ex.getLocalizedMessage());
    logger.error("拋異常了!"+ex.getLocalizedMessage());
    response.getWriter().printf(ex.getMessage());
    response.flushBuffer();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

這樣,Controller裏面的方法拋出了MissingServletRequestParameterException異常就會執行上面的這個方法來進行異常處理。 
像我下面的代碼

@RequestMapping("/index")
public String index(@MyUser User user,@RequestParam String id,ModelMap modelMap){
    return "login";
}
  • 1
  • 2
  • 3
  • 4

如果我沒有傳入id值,那麼就會拋出MissingServletRequestParameterException的異常,就會被上面的異常處理方法處理。

上面的@ExceptionHandler(MissingServletRequestParameterException.class)這個註解的value的值是一個Class[]類型的,這裏的ExceptionClass是你自己指定的,你也可以指定多個需要處理的異常類型,比如這樣@ExceptionHandler(value = {MissingServletRequestParameterException.class,BindException.class}),這樣就會處理多個異常了。

但這個只會是在當前的Controller裏面起作用,如果想在所有的Controller裏面統一處理異常的話,可以用@ControllerAdvice來創建一個專門處理的類。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章