【java】Execption的 e.getMessage()為null的解決方法


 

================================

場景:

  當代碼出現異常時通常都需要將異常信息寫入到日志中,異常信息越詳細越有利於問題的排查。而通過的Exception.getMessage()方法只能獲得異常的名稱而不能獲取哪里出現的異常,對於排錯意義不大。

甚至有時候,getMessage()返回的是null。

 

查看getMessage()的源碼:

/**
     * Returns the detail message string of this throwable.
     *
     * @return  the detail message string of this {@code Throwable} instance
     *          (which may be {@code null}).
     */
    public String getMessage() {
        return detailMessage;
    }

可以看到說明,與可能返回為null。

 

 

解決方法:

羅列四個解決方法

//1、
public String getTrace(Throwable t) {
    StringWriter stringWriter= new StringWriter();
    PrintWriter writer= new PrintWriter(stringWriter);
    t.printStackTrace(writer);
    StringBuffer buffer= stringWriter.getBuffer();
    return buffer.toString();
}
 
//2、
public static String getExceptionAllinformation(Exception ex){
        String sOut = "";
        StackTraceElement[] trace = ex.getStackTrace();
        for (StackTraceElement s : trace) {
            sOut += "\tat " + s + "\r\n";
        }
        return sOut;
}
 
//3、
public static String getExceptionAllinformation_01(Exception ex) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        PrintStream pout = new PrintStream(out);
        ex.printStackTrace(pout);
        String ret = new String(out.toByteArray());
        pout.close();
        try {
             out.close();
        } catch (Exception e) {
        }
        return ret;
}
 
//4、
private static String toString_02(Throwable e){  
         StringWriter sw = new StringWriter();  
         PrintWriter pw = new PrintWriter(sw, true);  
         e.printStackTrace(pw);  
         pw.flush();   
         sw.flush();  
         return sw.toString(); 
} 

 

 

 

具體使用場景:

          try {
                   .....

                }catch (Exception e){
                    StringWriter stringWriter= new StringWriter();
                    PrintWriter writer= new PrintWriter(stringWriter);
                    e.printStackTrace(writer);
                    StringBuffer buffer= stringWriter.getBuffer();
                    String errMsg = buffer.toString();

                    logger.error(errMsg);

                    hashMap.put("status",String.valueOf(-1));
                    hashMap.put("errorMsg",StringUtils.isBlank(errMsg) ? "" : errMsg);
                }finally {
                    redisUtil.HASH.hmset(recordKey,hashMap);
                    String lpop = redisUtil.LISTS.lpop(runTaskKey);
                    System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>任務執行完成,執行隊列"+runTaskKey+"移除:"+lpop);
                    hashMap.clear();
                }

 

 

 

 

參考地址:

https://blog.csdn.net/wjiaoling136/article/details/84903619

 


免責聲明!

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



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