天天看點

Spring MVC 處理異常的3種方式

三種方式

  • @ExceptionHandler

    标注的方法被定義為處理指定類型異常;
  • @ResponseStatus

    标注的方法執行,會修改響應頭中的狀态碼;
  • Spring會把

    @ControllerAdvice

    的類内部使用@ExceptionHandler方法應用到所有的 @RequestMapping注解的方法上

ExceptionHandler注解方式

注:

@ExceptionHandler

标注的方法,方法簽名靈活、多變。被@ResponseStatus注解的方法将會修改相應狀态碼,而使用

@ResponseBody

可以傳回json格式的資料,再供前端處理

/**
     * 使用者注冊
     * @param user
     * @return
     */
    @GetMapping("/register")
    public String register(User user){
        Assert.notNull(null,"request is null");
        userService.register(user);
        return "success";
    }

    /**
     * 目前控制器的異常處理
     */
//    @ResponseStatus(value = HttpStatus.BAD_REQUEST,reason = "參數異常")
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public String exceptionHandler(RuntimeException e){
        // 不做任何事或者可以做任何事
        return e.getMessage();
    }

           

全局異常處理

@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    public GlobalExceptionHandler() {
    }

    @ExceptionHandler({Exception.class})
    public String defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        log.error("---BaseException Handler---Host {} invokes url {} ERROR: ", new Object[]{req.getRemoteHost(), req.getRequestURL(), e});
        return JsonResUtil.respJson(CodeEnum.SERVICE_ERROR);
    }

    @ExceptionHandler({AppException.class})
    public String jsonErrorHandle(HttpServletRequest req, AppException e) {
        log.warn("---BaseException Handler---Host {} invokes url {}  ", req.getRemoteHost(), req.getRequestURL());
        return JsonResUtil.respJson(e.getCode(), e.getMessage());
    }
}
           

文章參考:

http://www.cnblogs.com/zhaohongtian/p/6807100.html