新建异常类 继承
public class HealthException extends RuntimeException {
public HealthException(String message) {
super(message);
}
}
创建异常处理类
@RestControllerAdvice
public class HealExceptionAdvice {
//定义方法做异常处理
//使用注解对异常进行认领
//统一标注返回类型
@ExceptionHandler(HealthException.class)
public Result handleHealthException(HealthException he) {
return new Result(false, he.getMessage());
}
//未知异常处理
@ExceptionHandler(Exception.class)
public Result handleException(Exception e) {
return new Result(false, "未知异常");
}
}
使用时候直接抛出异常
throw new HealthException(message);
网友评论