JSF 1.x generic exception handling
Asked Answered
I

6

16

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?

Inapproachable answered 20/1, 2009 at 9:37 Comment(0)
M
19

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.

Minta answered 20/1, 2009 at 11:5 Comment(1)
this was an excellent response, I wish I could give you 10 points for your answer.Betrothed
G
8

The JSF 2 now has a mechanism for handling exceptions:

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

Gloze answered 29/4, 2010 at 20:43 Comment(0)
L
6

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

Lid answered 28/4, 2011 at 21:6 Comment(0)
B
3

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.

Blatt answered 20/1, 2009 at 9:44 Comment(0)
B
1

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

Berard answered 24/1, 2009 at 13:20 Comment(0)
S
0

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

Savdeep answered 2/2, 2011 at 20:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.