1
resposta

Melhores práticas para tratamento de exceções em JSF e AJAX

Olá Nico,

Ao refatorar o FetchType.EAGER na classe livro, a tela executou, mas o erro na aplicação foi grave, pois os autores não foram carregados. Isso me chamou a atenção, uma vez que demais problemas como rede e banco, também poderão ocorrer em produção.

Por favor, quais as melhores práticas para tratamento de exceções e apresentação amigável aos usuários, utilizando JSF, AJAX e demais tecnologias do treinamento?

Parabéns pelas aulas e muito obrigado!

1 resposta

Bom dia Fernando, você pode utilizar classes que tratam as exceptions para você direcionando para páginas específicas. No código abaixo está um exemplo de como utilizar. No método handle da classe JsfExceptionHandler, caso seja uma ViewExpiredException, direcionar para /Principal.xhtml. Se for qualquer outra exception, direcionar para Erro.xhtml. Espero que estes exemplos te ajude. Att,

--- Classe JsfExceptionHandler ---
public class JsfExceptionHandler extends ExceptionHandlerWrapper {

    private ExceptionHandler wrapped;

    public JsfExceptionHandler(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();

            boolean handled = false;

            try {
                if (exception instanceof ViewExpiredException) {
                    handled = true;
                    redirect("/Principal.xhtml");
                } else {
                    handled = true;
                    redirect("/Erro.xhtml");
                }
            } finally {
                if (handled) {
                    events.remove();
                }
            }
        }

        getWrapped().handle();
    }

    private void redirect(String page) {
        try {
            FacesContext facesContext = FacesContext.getCurrentInstance();
            ExternalContext externalContext = facesContext.getExternalContext();
            String contextPath = externalContext.getRequestContextPath();

            externalContext.redirect(contextPath + page);
            facesContext.responseComplete();
        } catch (IOException e) {
            throw new FacesException(e);
        }
    }
}

--- Classe JsfExceptionHandlerFactory ---
public class JsfExceptionHandlerFactory extends ExceptionHandlerFactory {

    private ExceptionHandlerFactory parent;

    public JsfExceptionHandlerFactory(ExceptionHandlerFactory parent) {
        this.parent = parent;
    }

    @Override
    public ExceptionHandler getExceptionHandler() {
        return new JsfExceptionHandler(parent.getExceptionHandler());
    }

}

--- Configuração do faces-config.xml
<faces-config xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
    version="2.2">

    <factory>
        <exception-handler-factory>com.exemplo.JsfExceptionHandlerFactory</exception-handler-factory>
    </factory>

</faces-config>

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software