Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package br.com.service;
- import java.io.IOException;
- import java.util.Iterator;
- import javax.faces.FacesException;
- import javax.faces.application.FacesMessage;
- import javax.faces.context.ExceptionHandler;
- import javax.faces.context.ExceptionHandlerWrapper;
- import javax.faces.context.ExternalContext;
- import javax.faces.context.FacesContext;
- import javax.faces.event.ExceptionQueuedEvent;
- import javax.faces.event.ExceptionQueuedEventContext;
- import br.com.util.FacesUtil;
- public class ControleExceptionHandler extends ExceptionHandlerWrapper{
- private ExceptionHandler wrapped;
- public ControleExceptionHandler(ExceptionHandler wrapped) {
- this.wrapped = wrapped;
- }
- @Override
- public ExceptionHandler getWrapped() {
- return this.wrapped;
- }
- @Override
- public void handle() throws FacesException{
- Iterator<ExceptionQueuedEvent> events = getUnhandledExceptionQueuedEvents().iterator();
- while(events.hasNext()){
- ExceptionQueuedEvent event = events.next();
- ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource();
- Throwable exception = context.getException();
- UsuarioException usuarioException = getUsuarioException(exception);
- boolean handled = false;
- try {
- if (usuarioException != null){
- handled = true;
- FacesUtil.adicionarMensagem(FacesMessage.SEVERITY_ERROR, usuarioException.getMessage());
- } else {
- handled = true;
- redirect("/index.xhtml");
- }
- } finally {
- if(handled){
- events.remove();
- }
- }
- }
- getWrapped().handle();
- }
- private void redirect(String page){
- try{
- FacesContext fc = FacesContext.getCurrentInstance();
- ExternalContext ec = fc.getExternalContext();
- String contextPage = ec.getRequestContextPath();
- ec.redirect(contextPage + page);
- fc.responseComplete();
- } catch (IOException ioe){
- throw new FacesException(ioe);
- }
- }
- //metodo recursivo para interar em cada exceção da lista se existe uma exceção do tipo procurado
- private UsuarioException getUsuarioException(Throwable exception){
- if (exception instanceof UsuarioException){
- return (UsuarioException) exception;
- } else if (exception.getCause() !=null){
- return getUsuarioException(exception.getCause());
- }
- return null;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement