分布式项目统一异常处理
公共模块shop-common
1.异常后返回给前端的封装类
@Setter
@Getter
public class CodeMsg implements Serializable {
private int code;
private String msg;
public CodeMsg(int code, String msg) {
this.code = code;
this.msg = msg;
}
public CodeMsg(){
}
}
2.自定义异常
@Getter
@Setter
public class BusinessException extends RuntimeException {
private CodeMsg codeMsg;
public BusinessException(CodeMsg codeMsg) {
this.codeMsg = codeMsg;
}
public BusinessException() {
}
}
3.异常捕获,自身不贴增强控制器注解,其他模块需要抛异常时,直接继承这个类即可
public class CommonControllerAdvice {
@ExceptionHandler(BusinessException.class)
@ResponseBody
public Result handler(BusinessException e) {
e.printStackTrace();
e.getMessage();
return Result.error(e.getCodeMsg());
}
@ExceptionHandler(Exception.class)
@ResponseBody
public Result hanlderDefaultException(Exception e) {
e.printStackTrace();
return Result.defaultError();
}
}
4.返回给前端的统一类
@Setter
@Getter
public class Result<T> implements Serializable {
public static final int SUCCESS_CODE = 200;
public static final String SUCCESS_MESSAGE = "操作成功";
public static final int ERROR_CODE = 500;
public static final String ERROR_MESSAGE = "系统故障";
private int code;
private String msg;
private T data;
public Result() {
}
private Result(int code, String msg, T data) {
this.code = code;
this.msg = msg;
this.data = data;
}
public static <T>Result<T> success(T data){
return new Result<>(SUCCESS_CODE,SUCCESS_MESSAGE,data);
}
public static Result error(CodeMsg codeMsg){
return new Result(codeMsg.getCode(),codeMsg.getMsg(),null);
}
public static Result defaultError(){
return new Result(ERROR_CODE,ERROR_MESSAGE,null);
}
}
业务模块 member-server
1.异常信息封装类,继承公共模块CodeMsg
@Getter
@Setter
public class MemberCodeMsg extends CodeMsg {
public static final MemberCodeMsg LOGIN_ERROR=new MemberCodeMsg(50101,"账号或密码不能为空");
public static final MemberCodeMsg LOGIN_OPT=new MemberCodeMsg(50102,"账号或密码不正确");
public MemberCodeMsg(int code, String msg) {
super(code, msg);
}
public MemberCodeMsg() {
}
}
2.统一异常处理类,只需要继承CommonControllerAdvice即可
@ControllerAdvice
public class MemberControllerAdvice extends CommonControllerAdvice {
}
3.抛异常
@Service
public class UserServiceImpl implements IUserService {
@Autowired
private UserMapper userMapper;
@Override
public String doLogin(LoginVo loginVo) {
if (StringUtils.isEmpty(loginVo.getUsername())
|| StringUtils.isEmpty(loginVo.getPassword())) {
throw new BusinessException(MemberCodeMsg.LOGIN_ERROR);
}
long id = Long.parseLong(loginVo.getUsername());
User user = this.get(id);
if (user == null) {
throw new BusinessException(MemberCodeMsg.LOGIN_OPT);
}
String password = MD5Util.encode(user.getSalt(), loginVo.getPassword());
if (!password.equals(user.getPassword())) {
throw new BusinessException(MemberCodeMsg.LOGIN_OPT);
}
String token = createToken(user);
return token;
}
}
统一异常小结
1.公共模块,创建自定义异常类和统一异常捕获的类,但是不贴@ControllerAdvice注解,其他模块要用异常捕获时,
继承该类贴上@ControllerAdvice注解即可
2.公共模块建立CodeMsg类,里面封装状态码和信息,其他模块抛的具体异常信息继承该类,然后创建出对象即可
3.进行参数校验,不正确的地方抛自定义异常,自定义异常里面的信息是状态码和异常信息