2010-11-26 8 views
5

Siguiendo mi pregunta anterior en Creating FacesMessage in action method outside JSF conversion/validation mechanism?, trato de manejar las excepciones arrojadas desde la capa empresarial fuera de mis beans administrados.JSF 2: ¿Es este un buen enfoque para manejar las excepciones comerciales?

La estrategia es buscar y convertir excepciones de negocios a mensajes de caras en un PhaseListener ,.

Está funcionando como esperaba, pero me estoy preguntando si acabo de reinventar la rueda, o hacerlo bien con la forma incorrecta?

Aquí es mi muestra fragmento de código:

public class BusinessExceptionHandler implements PhaseListener { 

    @Override 
    public void afterPhase(PhaseEvent phaseEvent) { 
     ExceptionHandler exceptionHandler = phaseEvent.getFacesContext().getExceptionHandler(); 

     // just debugging the handled exception, nothing here 
     /* 
     for (ExceptionQueuedEvent event : exceptionHandler.getHandledExceptionQueuedEvents()) { 
      ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource(); 
      System.out.println("handled exception : " + context.getException()); 
     }*/ 

     for (Iterator<ExceptionQueuedEvent> it = exceptionHandler.getUnhandledExceptionQueuedEvents().iterator(); 
       it.hasNext();) { 

      ExceptionQueuedEvent event = it.next(); 
      ExceptionQueuedEventContext eventContext = (ExceptionQueuedEventContext) event.getSource(); 
      Throwable e = eventContext.getException(); 
      System.out.println("unhandled exception : " + e); 

      // get the root cause exception 
      while (e.getCause() != null) { 
       e = e.getCause(); 
      } 

      System.out.println("cause exception : " + e + 
       ", cause exception is BE : " + (e instanceof BusinessException)); 

      // handle BE 
      if (e instanceof BusinessException) { 
       BusinessException be = (BusinessException) e; 
       System.out.println("processing BE " + be); 
       FacesMessage message = Messages.getMessage(
        "com.corejsf.errors", 
        be.getMessage(), 
        be.getParamValues() 
       ); 
       FacesContext context = FacesContext.getCurrentInstance(); 
       context.addMessage(null, message); 
       it.remove(); // remove the exception 

       // works fine without this block, if BE is thrown, always return to the original page 
       /* 
       NavigationHandler navigationHandler = context.getApplication().getNavigationHandler(); 
       System.out.println("navigating to " + context.getViewRoot().getViewId()); 
       navigationHandler.handleNavigation(context, context.getViewRoot().getViewId(), null); 
       */ 
      } 
     } 
    } 

    @Override 
    public void beforePhase(PhaseEvent phaseEvent) { 
    } 

    @Override 
    public PhaseId getPhaseId() { 
     return PhaseId.INVOKE_APPLICATION; 
    } 

} 

Gracias!

Saludos, Albert Kam

Respuesta

2

Su enfoque es una mezcla de enfoques de manejo de excepciones JSF 1.x y JSF 2.x. Como está utilizando JSF 2.x, sugeriría un enfoque puro de JSF 2.x sin un PhaseListener y con la ayuda del nuevo ExceptionHandler API.

puede encontrar un ejemplo que trata el ViewExpiredException en la página 282 del libro "JSF 2.0: The Complete Reference" que está disponible en línea here (haga clic en el enlace primero resultado).

+0

Hola de nuevo. Gracias por la idea La página 282 no está disponible. Pero después de buscar en Google, encontré el artículo de edburn sobre este tipo de asunto, y utilizaré esta práctica más adelante: http://weblogs.java.net/blog/edburns/archive/2009/09/03/dealing-gracefully-viewexpiredexception- jsf2 – bertie

3

No sé por qué usted va esta ruta, crear y registrar su propio gestor de excepciones es realmente fácil. Aunque más fácil será Seam Catch (http://seamframework.org/Seam3/CatchModule y http://docs.jboss.org/seam/3/catch/3.0.0.Alpha1/reference/en-US/html_single/). Todavía no tengo un puente JSF, pero será muy fácil de hacer. Entonces, todo lo que tiene que hacer es escribir un método que manejará una excepción específica, ¡y habrá terminado!

+0

Todavía soy nuevo en el jsf y lleno de dudas sobre las mejores prácticas, de ahí la pregunta anterior :) Gracias por la sugerencia, aunque no estoy usando el marco de costura, voy a echar un vistazo sobre la api controlador de la excepción. – bertie

Cuestiones relacionadas