Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Getting the error Call Stack as a string

 
Carl Parrish
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I need to grab a thrown error call statck as a string (to pass to another page). What would be the best way to do this?
 
Michael Matola
whippersnapper
Ranch Hand
Posts: 1819
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do you use JUnit? I took a look at the JUnit source to see how it displays a stack trace in a JTextArea (in the SwingUI version). BaseTestRunner.getFilteredTrace is the workhorse method:


Since there's a version of printStackTrace that takes PrintWriter, they wrap a StringWriter with a PrintWriter, then pass it into printStackTrace. Then they build a String out of the StringWriter (using an intermediate StringBuffer -- I'm not clear on why they didn't just do String trace = stringWriter.toString()).
Anyhow, this is one way to do this. (Shamelessly stolen...)
Here's a less verbose version:

[ July 01, 2002: Message edited by: Michael Matola ]
 
Michael Matola
whippersnapper
Ranch Hand
Posts: 1819
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But wait, you said "page." Are you working with servlets? If so, don't even bother with the String and StringWriter, just call printStackTrace with you PrintWriter instance from HttpServletResponse as a parameter.
 
Carl Parrish
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually its a jsp page will it still work?
 
Michael Matola
whippersnapper
Ranch Hand
Posts: 1819
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry, don't know much about JSP. Take a look at this thread in the JSP forum. The poster seems to have the same question and has pretty much come up with the same solution. (I'm not clear where the "out" object is coming from in that example.)
 
Carl Parrish
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks your solution worked out great.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic