三种方式
-
@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());
}
}