0

如何将异常堆栈跟踪打印到网页?

import com.opensymphony.xwork2.ActionSupport;
import java.util.Arrays;

public class ExceptionAction extends ActionSupport 
{

 public String execute() 
 {      
    //
    String errMsg = Arrays.toString(Thread.currentThread().getStackTrace());

    this.addActionError(
                    "Unexcepted error has occurred. \n"
                    +errMsg
                    + "\nPlease try again or report this error to    administrator or support team. \n ");

    return "error";
 }

 /**
 * 
 */
 private static final long serialVersionUID = -3754090784536811052L;
}

但我得到了一个无用的味精使用上面的代码,味精是这样的:

    [java.lang.Thread.getStackTrace(Thread.java:1479),    com.monitoring.action.ExceptionAction.execute(ExceptionAction.java:11), sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method), sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39), 
4

2 回答 2

1

这是将堆栈跟踪打印到页面的代码

 package test;    
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TestServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

        PrintWriter out = response.getWriter();
        try {
            "test".charAt(20);
        } catch (RuntimeException e) {
            out.println("Stack Trace:<br/>");
            e.printStackTrace(out);
            out.println("<br/><br/>Stack Trace (for web display):</br>");
            out.println(displayErrorForWeb(e));
        }
    }

    public String displayErrorForWeb(Throwable t) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        t.printStackTrace(pw);
        String stackTrace = sw.toString();
        return stackTrace.replace(System.getProperty("line.separator"), "<br/>\n");
    }

}

来源:http ://www.avajava.com/tutorials/lessons/how-do-i-display-a-stack-trace-on-a-web-page.html

于 2013-06-22T07:27:14.207 回答
1

查看文档

File file = new File("test.log");
PrintStream ps = new PrintStream(file);
try {
    // something
} catch (Exception ex) {
    ex.printStackTrace(ps);
}
ps.close();

另请参见printStackTrace() 和 toString() 之间的区别

于 2013-06-22T07:20:10.647 回答