隨筆 全局異常處理spring @ExceptionHandler

爲了避免每次都try..catry,採用全局異常處理

請求:

  @PostMapping("/login")
    public String login(String password,String username) throws Exception{
          int i=1/0;
        }

全局異常處理類:

@RestControllerAdvice
public class MyException {

    @ExceptionHandler(Exception.class)
    public void exception(Exception e) {
        // 獲取request對象
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        System.out.println(("統一業務異常處理信息:{"+e.getMessage()+"}, URL : {"+ request.getRequestURL()+"}, METHOD : {"+ request.getMethod()+"}"));
    }
}

解釋兩個註解:@RestControllerAdvice和  @ExceptionHandler

@RestControllerAdvice:監控所有的@RequestMapping,捕獲它們的異常。

@ExceptionHandler: 所有該情形下的(Exception.class)異常就會交由我們規定好的@ExceptionHandler這個註解標記的方法裏處理。

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