Tuesday, May 5, 2009

Converting the exception stracktrace to string

Method 1 (using log4j):
 logger.error(ex, ex);  
Method 2 (without log4j):
 public String stackTraceString(Exception e) {  
      StringBuffer s = new StringBuffer();  
      StackTraceElement[] frames = e.getStackTrace();  
      for (int i=0; i < frames.length; i++) s.append(frames[i].toString()+"\n");  
      return new String(s);  
 }  
Method 3 (without log4j):
 /** Converts the exception stracktrace to string. */  
 public StringBuffer getExceptionStackTrace(Exception ex) {  
 StringWriter strWriter = new StringWriter();  
      if (null != ex) {  
           PrintWriter out = new PrintWriter(strWriter);  
           ex.printStackTrace(out);  
      }  
      return strWriter.getBuffer();  
 }  
 /** May be used to set the exception as fault content. */  
 public String getExceptionAsXmlText(Exception ex) {  
      if (null != ex) {  
           String message = ex.getMessage();  
           String stackTrace = getExceptionStackTrace(ex).toString();  
           String exXmlText = "<exception>" + 
           "<message>" + message + "</message>" +  
           "<stack-trace>" + stackTrace + "</stack-trace>" +  
           "</exception>" ;  
           return exXmlText;  
      }  
      return "";  
 }  

No comments: