三種方式
-
@ExceptionHandler標(biāo)注的方法被定義為處理指定類型異常; -
@ResponseStatus標(biāo)注的方法執(zhí)行,會修改響應(yīng)頭中的狀態(tài)碼; - Spring會把
@ControllerAdvice的類內(nèi)部使用@ExceptionHandler方法應(yīng)用到所有的 @RequestMapping注解的方法上
ExceptionHandler注解方式
注:@ExceptionHandler標(biāo)注的方法,方法簽名靈活、多變。被@ResponseStatus注解的方法將會修改相應(yīng)狀態(tài)碼,而使用@ResponseBody可以返回json格式的數(shù)據(jù),再供前端處理
/**
* 用戶注冊
* @param user
* @return
*/
@GetMapping("/register")
public String register(User user){
Assert.notNull(null,"request is null");
userService.register(user);
return "success";
}
/**
* 當(dāng)前控制器的異常處理
*/
// @ResponseStatus(value = HttpStatus.BAD_REQUEST,reason = "參數(shù)異常")
@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());
}
}