Java EE App的理想错误页面

我很难在我的应用程序中整合错误。 目前,我的error.jsp看起来如下(部分):

           

除了!之外的所有场景都可以正常工作:有时在我的应用程序中,我使用以下代码捕获MyException类中的内置exception:

 catch(MyException ex){ log.error(ex.getMessage(), uivex); String originalURL = "/errorpages/error.jsp?errorcode=" + (ex.getMajor() + ex.getMinor()) + "&errormessage=" + ex.getMessage(); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(address); dispatcher.forward(request,response); } 

现在的问题是,当我转发到error.jsp页面时…而不是看到来自MyException类的实际错误..我看到NullPointerException因为javax.servlet.error.status_code没有任何内容,并且页面被声明as isErrorPage="true"

在这种情况下我该怎么办? 一种解决方案是创建一个完全不同的error.jsp(将其命名为error1.jsp)页面,并将MyException类中的exception转发到该页面。 虽然,我想把所有东西放在一个地方。

这段代码老实地伤害了我的眼睛。 这是一个通用的应该是什么样子。 你可能会发现它很有用。

 <%@ page pageEncoding="UTF-8" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>     Error    

Error

Unfortunately an unexpected error has occurred. Below you can find the error details.

Details

  • Timestamp:
  • Action:
  • Exception:
  • Message:
  • Status code:
  • User agent:

@page isErrorPage仅在你想要在JSP中提供${exception} (即request.getAttribute("exception")时才有用。在这种特殊情况下你不需要它。

事实上,根本不要在catch区中前进。 放手吧。 然后它将由错误页面处理。

 } catch (MyException ex) { log.error(ex.getMessage(), uivex); throw ex; // Or throw new ServletException(ex.getMessage(), ex); } 

您可以创建自定义stackTrace jsp标记并将其包含在特殊错误页面中:

标签文件(WEB-INF / tags / stackTrace.tag)

 <%@tag description="Prints stack trace of the specified Throwable" pageEncoding="UTF-8"%> <%-- content (prints stack trace) --%> <% java.io.PrintWriter pOut = new java.io.PrintWriter(out); try { // The Servlet spec guarantees this attribute will be available Throwable err = (Throwable) request.getAttribute("javax.servlet.error.exception"); if(err != null) { if(err instanceof ServletException) { // It's a ServletException: we should extract the root cause ServletException se = (ServletException) err; Throwable rootCause = se.getRootCause(); if(rootCause == null) { rootCause = se; } out.println("** Root cause is: " + rootCause.getMessage()); rootCause.printStackTrace(pOut); }else { // It's not a ServletException, so we'll just show it err.printStackTrace(pOut); } }else { out.println("No error information available"); } // Display cookies out.println("\nCookies:\n"); Cookie[] cookies = request.getCookies(); if(cookies != null) { for(int i = 0; i < cookies.length; i++) { out.println(cookies[i].getName() + "=[" + cookies[i].getValue() + "]"); } } }catch(Exception ex) { ex.printStackTrace(pOut); } %> 

error.jsp可能是这样的:(添加一些幽默,如果你的应用程序有点随意)

 <%@ page isErrorPage="true" %>   Error   

“报告此错误”按钮可以提交堆栈跟踪或邮寄它!

将所有详细信息放在日志中,并向用户显示一个模糊的消息,表明出现了问题,无论exception是什么。 所以你的错误页面可能看起来像(引用twitter):

 <%@ page isErrorPage="true" %> Something went technically wrong. 

并且不要捕捉和前进 – 只是让exception泡沫。 另一种选择是,正如您所说,制作两个包含公共内容的单独页面,并且仅在isErrorPage定义中有所不同。