View Javadoc

1   /*
2    * ExceptionToString.java
3    *
4    * Created on 26. cerven 2007, 17:32
5    *
6    * To change this template, choose Tools | Template Manager
7    * and open the template in the editor.
8    */
9   
10  package cz.cuni.amis.utils;
11  
12  import java.io.PrintWriter;
13  import java.io.StringWriter;
14  
15  /**
16   * Simple class that serialize (format) exception to the String allowing you to
17   * specify a message as a prefix of the whole string.
18   * 
19   * @author Jimmy
20   */
21  public class ExceptionToString {
22  
23  	public static String process(String message, Throwable e) {
24  		StringBuffer sb = new StringBuffer();
25  		if (message != null) {
26  			sb.append(message);
27  			sb.append(Const.NEW_LINE);
28  		}
29  		Throwable cur = e;
30  		if (cur != null) {
31  			sb.append(cur.getClass().getName() + ": " + cur.getMessage() +
32  					cur.getStackTrace() == null || cur.getStackTrace().length == 0 ? 
33  							" (at UNAVAILABLE)"
34  						:	" (at " + cur.getStackTrace()[0].toString() + ")"
35  			);
36  			cur = cur.getCause();
37  			while (cur != null) {
38  				sb.append(Const.NEW_LINE);
39  				sb.append("caused by: ");
40  				sb.append(cur.getClass().getName() + ": " + cur.getMessage() + 
41  						cur.getStackTrace() == null || cur.getStackTrace().length == 0 ? 
42  								" (at UNAVAILABLE)"
43  							:	" (at " + cur.getStackTrace()[0].toString() + ")"
44  				);
45  				cur = cur.getCause();
46  			}
47  			sb.append(Const.NEW_LINE);
48  			sb.append("Stack trace:");
49  			sb.append(Const.NEW_LINE);
50  			StringWriter stringError = new StringWriter();
51  			PrintWriter printError = new PrintWriter(stringError);
52  			e.printStackTrace(printError);
53  			sb.append(stringError.toString());
54  		}
55  		return sb.toString();
56  	}
57  
58  	public static String process(Throwable e) {
59  		return process(null, e);
60  	}
61  	
62  	public static String getCurrentStackTrace() {
63  		Exception e = new Exception();
64  		StringWriter stringError = new StringWriter();
65  		PrintWriter printError = new PrintWriter(stringError);
66  		e.printStackTrace(printError);
67  		return stringError.toString();
68  	}
69  
70  }