ErrorCode枚舉類型返回錯誤碼信息測試,手動拋出異常信息,在事務中根據錯誤碼來回滾事務的思路。


ErrorCode.java 簡單測試代碼,具體應用思路:手動拋出異常信息,在事務中根據錯誤碼來回滾事務的思路。

public enum ErrorCode {
    //系統級
    SUCCESS("000000","success"), 
    SYS_ERROR("999999","系統異常"),
    FAILED("900000","操作失敗!"),
    //交易部分
    OWNER_NOT_EXIST("500002","用戶(車主)不存在"),
    ;
    
    private String code;
    private String text;
    
    private ErrorCode(String code, String text) {   
        this.code = code;   
        this.text = text;   
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }
    
    public String getText() {
        return text;
    }
    
    public void setText(String text) {
        
        this.text = text;
    } 

    
    public static void main(String[] args) {

        ErrorCode error = ErrorCode.FAILED;
        try {
            error = testFun(100);    //測試方法。
        } catch (Exception e) {
            System.err.println("e: " + e);
            String errorMsg = e.getMessage(); 
            System.err.println("errorMsg: " + errorMsg);
            System.err.println("errorMsg2: " + e.getLocalizedMessage());
            
            if(errorMsg != null){
                String[] msg = errorMsg.split(",");
                if(msg != null && msg.length > 0){
                    ErrorCode.SYS_ERROR.setCode(msg[0]);
                    ErrorCode.SYS_ERROR.setText(msg[1]);                
                }
            }
            //返回錯誤碼
            error = ErrorCode.SYS_ERROR;
            System.err.println("code: " + error.getCode() );
            System.err.println("text: " + error.getText() );
            
        }
        
    }

    private static ErrorCode testFun(int i) throws Exception {
        System.err.println("接收到的參數值:" + i);
        ErrorCode error = ErrorCode.OWNER_NOT_EXIST;
        String errorMsg = error.getCode() + "," + error.getText();  //將異常信息返回。
        throw new Exception(errorMsg);      //手動拋出異常。
//        throw new Exception();      //手動拋出異常。
        //return null;
    }
}
 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM