Ajuda com ExceptionHandler

2 respostas
A

Oiê :)

Galera, estou estudando tratamento de exceção com Struts, mais especificamente, com ExceptionHandler, porém, o meu exemplo não funcionou. :x

Garimpei alguns pedaços na internet... abaixo segue o código que eu "montei":

Explicando: O erro ocorre na classe de persistência quando um usuário tenta cadastrar um cliente com um login que já existe, pois na tabela usuario o login está especificado como unique.
Quem invoca o método insertUser da persistência é a Action IncludeUserAction.

Acredito que está faltando alguma coisa... mas o que :?:
Não estou conseguindo descobrir sozinha, preciso da ajuda de vcs!

Desde já agradeço qq ajuda!

[]'s :wink:

Classe herdeira de Exception :shock:
package strutsdemo.exception;

public class STException extends Exception{
    
    protected Throwable causaRaiz = null;
    private String messageKey = null;
    private Object[] messageArgs = null;
    
    public STException (){ 
        super();
    }
    
    public STException (String messageKeyLoc, Object[] messageArgsLoc, Throwable causa) {
        setMessageKey(messageKeyLoc);
        setCausaRaiz(causa);
        setMessageArgs(messageArgsLoc); 
    }   
   
    
    public STException (Throwable causa ) {
        this.causaRaiz = causa;
    }
    
    public STException (String novaMessageKey) {
        this.messageKey = novaMessageKey; 
    }
    
    public void setMessageKey( String key ) {
       this.messageKey = key; 
    }
    
    public String getMessageKey () {
       return messageKey; 
    }
    
    public void setMessageArgs( Object[] args ) {
        this.messageArgs = args; 
    }
    
    public Object[] getMessageArgs() {
        return messageArgs; 
    }
    
    public void setCausaRaiz(Throwable anException) {
       causaRaiz = anException;
    }
    
    public Throwable getCausaRaiz() {
     return causaRaiz; 
    }
}

Classe herdeira de ExceptionHandler :shock:

public class PICExceptionHandler extends ExceptionHandler{
   private transient final Log log = LogFactory.getLog(PICExceptionHandler.class);
        
    public ActionForward execute( Exception ex, ExceptionConfig config, ActionMapping mapping,
                 ActionForm formInstance, HttpServletRequest request, HttpServletResponse response)
                 throws ServletException{     

  ActionForward forward =  super.execute(ex, config, mapping, formInstance, request, response);

        ActionMessage error = null;
        String property = null;

        if (ex instanceof Exception && forward == null) {
            storeException(request, "", new ActionMessage("errors.detail", ex.getMessage()), forward);
            try {
                response.sendError(HttpServletResponse.SC_FORBIDDEN);                
                return null;
            } catch (IOException io) {
                io.printStackTrace();
                log.error(io.getMessage());
            }
        }
        
      }

protected void storeException(HttpServletRequest request, String property,
                                  ActionMessage error, ActionForward forward) {
        ActionMessages errors =
            (ActionMessages) request.getAttribute(Globals.ERROR_KEY);

        if (errors == null) {
            errors = new ActionMessages();
        }

        errors.add(property, error);

        request.setAttribute(Globals.ERROR_KEY, errors);
    }
}
Classe Action :shock:
public class IncludeUserAction extends Action{
     @Override
      public ActionForward execute(ActionMapping mapping,  ActionForm form, 
                                                    HttpServletRequest request, HttpServletResponse response) throws Exception {
         
       ...
         
                if( !errors.isEmpty( ) )
                    return mapping.findForward( "errors.detail" );
              
         
         return mapping.findForward("success");
      }
}
struts-config.xml :shock:
<global-exceptions>
        <exception
        type="strutsdemo.exception.STExceptionHandler"
        key="errors.detail"
        path="/pages/erro2.jsp" />
     
    </global-exceptions>
Classe Persistência (onde ocorre a exceção) :shock:
public static void insertUser(Usuario user) throws STException {  
        PreparedStatement stmt = null;
        ResultSet rs = null;
       
        try {        
            conn = ConnectionManager.getConnection( );
            stmt = conn.prepareStatement(
                "INSERT INTO strutsdemo.usuario (\n" +
                "id_usuario, nome, login, senha, sexo, ativo, faixa_idade\n" +
                ") VALUES (?, ?, ?, ?, ?, ?, ?)");
            stmt.setInt(1, getNextUserId(conn));
            stmt.setString(2, user.getNome());
            stmt.setString(3, user.getLogin());
            stmt.setString(4, user.getSenha());
            stmt.setString(5, user.getSexo());
            stmt.setBoolean(6, user.getAtivo());
            stmt.setInt(7, user.getFaixaIdade());
            stmt.executeUpdate();
            
        }catch( ClassNotFoundException cex){
             throw new   STException ( "error.classe.found", new Object[ ] {cex}, cex );
        }catch(SQLException sqlex){
               throw new STException ( "error.sql", new Object[ ] {sqlex}, sqlex );
        }catch(IllegalArgumentException illex){
               throw new STException ( "error.sem.conexao", new Object[ ] {illex}, illex );
        }catch(Exception ex){
               throw new STException ( "error.global", new Object[ ] {ex}, ex );
        }
        finally {
            try{
                if (rs != null) {
                    rs.close();
                }
                if (stmt != null) {
                    stmt.close();
                }
            }catch(Exception e ){
                throw new STException (e.getMessage( ), new Object[ ] {e}, e );
            }
            
            ConnectionManager.closeConnection();
        }
    }

2 Respostas

A

:cry: Galera, eu realmente preciso desta informação.
Aqui na empresa, estou sendo responsável sozinha por um projeto em Struts,
sendo que este é o meu 1º trabalho com java. Aqui no trabalho, só eu sei java, então não tenho com quem tirar dúvidas.

Agradeço a qualquer um que tenha a bondade de ajudar :roll:

R

Anastasia, em seu , você colocou type=“strutsdemo.exception.STExceptionHandler”, porém você não tem essa classe (STExceptionHandler) e sim STException, você tem também PICExceptionHandler… creio que seja a classe a ser configurada no struts-config. Então tente substituir por type=“strutsdemo.exception.PICExceptionHandler” ok?

Criado 11 de julho de 2008
Ultima resposta 7 de ago. de 2009
Respostas 2
Participantes 2