@ExceptionHandler 異常處理

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

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

@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();
}

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

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

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

上面的@ExceptionHandler(MissingServletRequestParameterException.class)這個註解的value的值是一個Class[]類型的,這裏的ExceptionClass是你本身指定的,你也能夠指定多個須要處理的異常類型,好比這樣@ExceptionHandler(value = {MissingServletRequestParameterException.class,BindException.class}),這樣就會處理多個異常了。io

但這個只會是在當前的Controller裏面起做用,若是想在全部的Controller裏面統一處理異常的話,能夠用@ControllerAdvice來建立一個專門處理的類。class

相關文章
相關標籤/搜索