Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Storing stacktrace of an exception to the database.

 
Alok Pota
Ranch Hand
Posts: 185
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When an exception is thrown, you can print the stacktrace to the default PrintWriter (System.out) or a specified PrintWriter. However if I wanted to log the exception
stacktrace to the database how do I get the stacktrace?
I know there is a toString() function of the exception but that does not give the stack trace.
 
Alok Pota
Ranch Hand
Posts: 185
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class ExceptionWriter extends PrintWriter {
public ExceptionWriter() {
super(new StringWriter());
}
public ExceptionWriter(OutputStream out) {
super(out);
}
public ExceptionWriter(OutputStream out, boolean autoFlush) {
super(out, autoFlush);
}
public ExceptionWriter(Writer out) {
super(out);
}
public ExceptionWriter(Writer out, boolean autoFlush) {
super(out, autoFlush);
}

public StringBuffer getBuffer() {
if (super.out instanceof StringWriter) {
return ((StringWriter)out).getBuffer();
}
throw new IllegalArgumentException("Underlying writer is not a StringWriter");
}
}

to use the above
Throwable t;
ExceptionWriter ew = new ExceptionWriter();
t.printStackTrace(ew);
String stackTrace = ew.getBuffer().toString();
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic