Search This Blog

Showing posts with label jsf 2. Show all posts
Showing posts with label jsf 2. Show all posts

Tuesday, September 21, 2010

JSF 2 Exception Handling

JSF 2 introduced ExceptionHandler as central point for handling unexpected Exceptions that are thrown during the Faces lifecycle.

To avoid silent exceptions that are not catched in application implement your ExceptionHandler and do what ever you want with exception.

1. Create your implementation of ExceptionHandler:
public class MyExceptionHandler extends ExceptionHandlerWrapper {

  private static Log log = LogFactory.getLog(MyExceptionHandler.class);
  private ExceptionHandler wrapped;

  public MyExceptionHandler(ExceptionHandler wrapped) {
    this.wrapped = wrapped;
  }

  @Override
  public ExceptionHandler getWrapped() {
    return wrapped;
  }

  @Override
  public void handle() throws FacesException {
    //Iterate over all unhandeled exceptions
    Iterator i = getUnhandledExceptionQueuedEvents().iterator();
    while (i.hasNext()) {
      ExceptionQueuedEvent event = i.next();
      ExceptionQueuedEventContext context =
        (ExceptionQueuedEventContext)event.getSource();

      //obtain throwable object
      Throwable t = context.getException();

      //here you do what ever you want with exception
      try{
      //log error
        log.error("Serious error happened!", t);
        //redirect to error view etc....  
      }finally{
        //after exception is handeled, remove it from queue
        i.remove();
      }
    }
    //let the parent handle the rest
    getWrapped().handle();
  }
}
2. Create your ExceptionHandlerFactory and call your ExceptionHandler:
public class MyExceptionHandlerFactory extends ExceptionHandlerFactory {

  private ExceptionHandlerFactory parent;

  // this injection handles jsf
  public MyExceptionHandlerFactory(ExceptionHandlerFactory parent) {
    this.parent = parent;
  }

  //create your own ExceptionHandler
  @Override
  public ExceptionHandler getExceptionHandler() {
    ExceptionHandler result =
        new MyExceptionHandler(parent.getExceptionHandler());
    return result;
  }
}
3. Register your exception handler factory in faces-config.xml:
<factory>
  <exception-handler-factory>
    test.MyExceptionHandlerFactory
  </exception-handler-factory>
</factory>