JSF 1.x通用异常处理

16

如果我的业务层出现异常(例如,在我的JDBC连接bean中发生了SQL异常),我如何传播它并附带自定义消息到全局的error.jsp页面?

6个回答

19

JSF 1.x没有提供任何隐式的这种类型的错误处理,但你可以使用导航规则重定向到一个错误页面(假设为表单提交)...

<navigation-case>
<description>
Handle a generic error outcome that might be returned
by any application Action.
</description>
<display-name>Generic Error Outcome</display-name>
<from-outcome>loginRequired</from-outcome>
<to-view-id>/must-login-first.jsp</to-view-id>
</navigation-case>

...或者使用重定向...

FacesContext context = FacesContext.getCurrentInstance();
ExternalContext extContext = context.getExternalContext();
String url = extContext.encodeActionURL(extContext
        .getRequestContextPath()
        + "/messages.faces");
extContext.redirect(url);
我建议查看JSF规范,以获取更多详细信息。
错误消息可以放置在请求作用域/会话作用域/URL参数中,根据您的喜好选择。
假设使用Servlet容器,则可以使用常规的web.xml错误页面配置
<error-page>
    <exception-type>java.lang.Exception</exception-type>
    <location>/errorPage.faces</location>
</error-page>

在您的后端bean中,您可以将受检异常包装并抛出为RuntimeException

一些JSF实现/框架会捕获这些错误(Apache MyFaces/Facelets),因此您需要配置它们不要


这是一个非常出色的回答,我希望我能给你的回答打10分。 - Richard Clayton

8

6

我在网站中制作了一个错误页面,并放置了错误的堆栈跟踪信息。这段代码首先需要放置在web.xml文件中。

<error-page>
                <error-code>500</error-code>
                <location>/errorpage.jsf</location>
</error-page>

当jsf页面有这段代码时:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"   
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      >
<h:head>
    <h:outputStylesheet name="EstilosOV.css" library="css" />
    <!-- <h:outputScript name="sincontext.js" library="scripts"/> -->

</h:head>
<h:body >
<table width="338" border="0" align="center" bordercolor="#FFFFFF">

    <tr bgcolor="#1D2F68">
      <td colspan="4" height="35" class="TablaHeader2"> PLAN SEGURO</td>
    </tr>
    <tr  bgcolor="#FDF2AA">
    <td colspan="4"  class="HeaderExcepcion">
      <h:graphicImage library="images" name="errormark.jpg"/>
      <font size="5px" color="#CC0000" >Error de ejecución</font>
      </td>
    </tr>
    <tr >
    <td colspan="3" class="anuncioWarning2">Ocurrio un error al realizar la operación, favor de intentarlo nuevamente, si el error aún se presenta, favor de notificarlo a soporte técnico al 5147-31-00 extensión 6893</td>
    </tr>
    <tr>
      <td height="17" colspan="3" class="TablaHeader2"></td>
    </tr>

</table>
    <h:form id="formerror">
        <h:inputHidden id="valuestack" value="#{errorDisplay.stackTrace}"></h:inputHidden>
    </h:form>
</h:body>

</html>

请注意,Motif 可以让您调试堆栈跟踪,以了解隐藏字段中的异常原因。现在我们来看一下该类如何定义以恢复 StackTrace。
public class ErrorDisplay implements Serializable{

    private static final long serialVersionUID = 6032693999191928654L;
    public static Logger LOG=Logger.getLogger(ErrorDisplay.class);

    public String getContacto() {
        return "";
    }

    public String getStackTrace() {
        FacesContext context = FacesContext.getCurrentInstance();
        Map requestMap = context.getExternalContext().getRequestMap();
        Throwable ex = (Throwable) requestMap.get("javax.servlet.error.exception");

        StringWriter writer = new StringWriter();
        PrintWriter pw = new PrintWriter(writer);
        fillStackTrace(ex, pw);
        LOG.fatal(writer.toString());

        return writer.toString();
    }

    private void fillStackTrace(Throwable ex, PrintWriter pw) {
        if (null == ex) {
            return;
        }

        ex.printStackTrace(pw);

        if (ex instanceof ServletException) {
            Throwable cause = ((ServletException) ex).getRootCause();

            if (null != cause) {
                pw.println("Root Cause:");
                fillStackTrace(cause, pw);
            }
        } else {
            Throwable cause = ex.getCause();

            if (null != cause) {
                pw.println("Cause:");
                fillStackTrace(cause, pw);
            }
        }
    }
}

当你完成在facesconfig文件中的bean定义时,它已经被附加上了。

<managed-bean>
            <description>
                Bean que sirve para llenar la especificacion de un error. Stacktrace 
            </description>
            <managed-bean-name>errorDisplay</managed-bean-name>
            <managed-bean-class>mx.com.tdc.datos.page.bean.ErrorDisplay</managed-bean-class>
            <managed-bean-scope>session</managed-bean-scope>
        </managed-bean>

And I hope that this will serve


3
在JSF中向用户显示错误消息的一般方法是使用FacesMessage:
在Java端:
...
if (errorOccurred) {
    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("An error occurred blabla..."));
}

在JSF(JSP或XHTML)页面中,只需在页面中使用<h:messages/>组件来显示错误信息。

1

1

你可以放置

<%@ page errorPage="error.jsp" %>

在您的JSP/JSF页面中,在error.jsp中,您将会有:

<%@ page isErrorPage="true" %>

设置isErrorPage="true"将会给你的页面另一个隐式对象:exception(就像你已经在jsp页面上有了request和response一样)。然后你可以从exception中提取信息。

更多细节


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接