JSF 1.x generic exception handling

霸气de小男生 提交于 2019-12-20 10:12:10

问题


If I have an exception in my business layer (e.g. a SQL exception in my JDBC connection bean), how can I propagate it with a custom message to a global error.jsp page?


回答1:


JSF 1.x doesn't provide any implicit error handling of this type, though you can redirect to an error page using navigation rules (assuming a form post)...

<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>

...or using a redirect...

FacesContext context = FacesContext.getCurrentInstance();
ExternalContext extContext = context.getExternalContext();
String url = extContext.encodeActionURL(extContext
        .getRequestContextPath()
        + "/messages.faces");
extContext.redirect(url);

I recommend looking at the JSF specification for more details.

Error messages can be placed on the request scope/session scope/url parameters, as you like.


Assuming a Servlet container, you can use the usual web.xml error page configuration.

<error-page>
    <exception-type>java.lang.Exception</exception-type>
    <location>/errorPage.faces</location>
</error-page>

In your backing bean, you can wrap and throw your checked exceptions in RuntimeExceptions.

Some JSF implementations/frameworks will catch these errors (Apache MyFaces/Facelets), so you'll have to configure them not to.




回答2:


The JSF 2 now has a mechanism for handling exceptions:

http://java.sun.com/javaee/6/docs/api/javax/faces/context/ExceptionHandler.html




回答3:


I made ​​an error page in the site faces and put the stacktrace of the error This code first put it in the web.xml

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

While the jsf page had this code

<?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>

Note that motif lets you debug the stacktrace for an reazon know which is the exception in the hidden field. Let's see how the class is defined recovers 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);
            }
        }
    }
}

and already attached as you finish this bean definition in the file facesconfig

<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




回答4:


The general way to display error message to the user in JSF is to use FacesMessage:

On Java side:

...
if (errorOccurred) {
    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("An error occurred blabla..."));
}

and in the JSF (JSP or XHTML) page, simply use the <h:messages/> component in your page in order to display the error.




回答5:


You can put

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

in jour jsp/jsf page. In error.jsp, jou would have:

<%@ page isErrorPage="true" %>

isErrorPage="true" will give your page another implicit object: exception (the same way you already have request and response on jsp page). You can then extract message from exception.

Additional details




回答6:


I came to same problem and found link describing how you can use ExceptionHandler in JSF2:

http://jugojava.blogspot.com/2010/09/jsf-2-exception-handling.html



来源:https://stackoverflow.com/questions/460596/jsf-1-x-generic-exception-handling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!