How to use exception gracefully in actual development (Java)

Keywords: enum + custom exception

Suitable for learning groups: back-end development, Java beginners, interview candidates.

Exception code enumeration

First define an exception code enumeration processing

public enum ErrorCodeEnum {
    
    
    SYS_ERROR("SYS_ERROR","系统错误,请重写"),
    UNKOWN_ERROR("UNKOWN_SYS_ERROR","未知的系统异常"),
    SERVICE_INVOKE_FAIL("SERVICE_INVOKE_FAIL", "服务调用失败"),
    ILLEGAL_ARGS("ILLEGAL_ARGS", "参数校验错误"),
    ;

    /**
     * 结果异常
     */
    private String code;
    /**
     * 描述
     */
    private String decs;

    ErrorCodeEnum(String code, String decs) {
    
    
        this.code = code;
        this.decs = decs;
    }

    public static ErrorCodeEnum getByValue(String code){
    
    
        for (ErrorCodeEnum result : values()) {
    
    
            if (code.equals(result.getCode())){
    
    
                return result;
            }
        }
        return null;
    }

    public String getCode() {
    
    
        return code;
    }

    public void setCode(String code) {
    
    
        this.code = code;
    }

    public String getDecs() {
    
    
        return decs;
    }

    public void setDecs(String decs) {
    
    
        this.decs = decs;
    }
}

A method to find enumeration through code
Insert picture description here

Custom exception

Note that there is an exception enumeration that
inherits RuntimeException

/**
 * 自定义异常
 */
public class KomaException extends RuntimeException {
    
    
    private static final long serialVersionUID = -8581672033133636908L;
    /*** 错误码枚举*/
    private ErrorCodeEnum errorCode;
    /**
     * 详细错误信息
     */
    private Map<String, String> errorMap = new HashMap<String, String>();
    /**
     * 带参构造器.
     *
     * @param errorCode
     */
    public KomaException(ErrorCodeEnum errorCode) {
    
    
        super(errorCode.getDecs());
        this.setErrorCode(errorCode);
    }
    /**
     * 带参构造器.
     *
     * @param errorCode
     * @param message
     */
    public KomaException(ErrorCodeEnum errorCode, String message) {
    
    
        super(message.isEmpty() ? errorCode.getDecs() : message);
        this.setErrorCode(errorCode);
    }

    /**
     * 带参构造器.
     *
     * @param errorCode
     * @param errorMap
     */
    public KomaException(ErrorCodeEnum errorCode, Map<String, String> errorMap) {
    
    
        this(errorCode);
        this.errorMap = errorMap;
    }
    /**
     * 带参构造器.
     *
     * @param message
     */
    public KomaException(String message) {
    
    
        super(message);
        this.setErrorCode(ErrorCodeEnum.UNKOWN_ERROR);
    }
    /**
     * Gets error code.
     *
     * @return the error code
     */
    public ErrorCodeEnum getErrorCode() {
    
    
        return errorCode;
    }
    /**
     * Sets error code.
     *
     * @param errorCode the error code
     */
    public void setErrorCode(ErrorCodeEnum errorCode) {
    
    
        this.errorCode = errorCode;
    }
    /**
     * Gets error map.
     *
     * @return the error map
     */
    public Map<String, String> getErrorMap() {
    
    
        return errorMap;
    }
    /**
     * Sets error map.
     *
     * @param errorMap the error map
     */
    public void setErrorMap(Map<String, String> errorMap) {
    
    
        this.errorMap = errorMap;
    }
    private static String findMessage(Map<String, String> errorMap) {
    
    
        if (errorMap.isEmpty()) {
    
    
            return null;
        }
        return errorMap.values().iterator().next();
    }
}

2 construction methods, you can also add other default construction methods,
one is based on the exception code enumeration, the other is exception code enumeration and exception description
Insert picture description here

Test class

The catch here can encapsulate a resut object, encapsulating the exception code, exception description, and success or failure

public class Test {
    
    
    public static void main(String[] args) {
    
    
        String name=null;
        int i=0;
        try{
    
    
            if (name==null){
    
    
                throw new KomaException(ErrorCodeEnum.ILLEGAL_ARGS);
            }
            if (i==0){
    
    
                throw new KomaException(ErrorCodeEnum.ILLEGAL_ARGS,"参数不能为0");

            }
        }catch (KomaException e){
    
    
            e.printStackTrace();
            System.out.println("异常码:"+e.getErrorCode().getCode());
            System.out.println("异常描述:"+e.getMessage());
        }
    }
}

The exception code and exception information have been typed out, and it is a very method to locate the problem
Insert picture description here

to sum up

You can define the exception code class. If the business is very complex, you can create a few more exception code classes
. One exception class in the project is enough. Different exception code definitions are used to distinguish business exceptions. It is
strongly recommended to define more exception codes during development. The better, it is convenient for production to quickly locate the BUG
key enumeration exception code + custom exception

Guess you like

Origin blog.csdn.net/weixin_46011971/article/details/107025552