另一个java自定义异常

有时候为了简化业务判断,可以抛出自定义异常,然后在最顶层,根据异常信息返回不用的信息。

定义系统异常基类:

public class BusinessException extends Exception {
private static String baseMsg = "business exception:";
public BusinessException(String msg) {
super(baseMsg+msg);
}
}

子类1:

public class OpenIdIsEmptyException  extends BusinessException {
private static String msg = "openId is empty";
public OpenIdIsEmptyException() {
super(msg);
}
}

子类2:

public class UserIsNotExistException extends BusinessException {
private static String msg = "user is not exist";
public UserIsNotExistException() {
super(msg);
}
}

底层抛出

}else{
logger.info("userName:{} is not exist",userName);
throw new UserIsNotExistException();
}

方法抛出

throws OpenIdIsEmptyException, UserIsNotExistException 

顶层捕获

} catch (UserIsNotExistException e) {
e.printStackTrace();
logger.info("UserIsNotExistException"+e.getMessage());
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
}

自定义异常

异常基类:

package combiz.exception;
public class BusinessException extends Exception {
     protected String msg ;
     private static final long serialVersionUID = 1L;
     public String getMessage() {
         return msg;
     }
}

主体异常:业务系统主体信息报错异常

package combiz.exception;
public class SubjectException extends BusinessException{
private static final long serialVersionUID = 1L;
}

主体未找到异常

package combiz.exception;
public class SubjectNotFoundException extends SubjectException{
    private static final long serialVersionUID = 1L;
}

企业信息未找到异常

package combiz.exception;
public class CompanyNotFoundException extends SubjectNotFoundException{
    private static String msg =new ExceptionCodeMsg("001", "企业未找到").getMsg() ;

    public CompanyNotFoundException(){
        super.msg = msg;
    }
}

异常编码类

package combiz.exception;
public class ExceptionCodeMsg {
   private String code;
   private String msg;
   public ExceptionCodeMsg(String code,String msg){
       this.code = code;
       this.msg = msg;
   }
   public String getMsg(){
       return "错误码:"+code+",错误信息:"+msg;
   }
 }