Struts 2 - How to redirect exceptions of type Exception to a particular page, but not handle a particular exception?

前端 未结 1 1730
攒了一身酷
攒了一身酷 2020-12-10 20:47

I wish to redirect all errors of type Exception to the result \"error\". For that, I did this :



        
1条回答
  •  眼角桃花
    2020-12-10 21:24

    Use instanceof operator and rethrow desired exception from exception handler.

    I managed it with an interceptor (here is what I used to try it out):

    package com.kenmcwilliams.interceptor;
    
    import com.opensymphony.xwork2.ActionContext;
    import com.opensymphony.xwork2.ActionInvocation;
    import com.opensymphony.xwork2.interceptor.Interceptor;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    
    public class Rethrower implements Interceptor{
        @Override
        public void destroy() {
        }
    
        @Override
        public void init() {
        }
    
        @Override
        public String intercept(ActionInvocation invocation){
            System.out.println("Start rethrower!");
            String result = "success";
            try {
                result = invocation.invoke();
            } catch (Exception ex) {
                Logger.getLogger(Rethrower.class.getName()).log(Level.SEVERE, null, ex);
            }
            Object exception = ActionContext.getContext().getValueStack().findValue("exception");
            if (exception instanceof RuntimeException){
                System.out.println("DOING RETHROW!");
                RuntimeException e = (RuntimeException)exception;
                throw e;
            }
            System.out.println("After rethrower!");
            return result;
        }
    }
    

    Here is the struts.xml (to save time looking up struts dtd):

    
    
    
    
        
        
        
            
                
                
                    
                    
                
            
            
                /WEB-INF/content/error.jsp
            
            
                
            
            
                
                /WEB-INF/content/bomb.jsp
            
        
    
    

    Finally the action (it just throws a runtime exception):

    package com.kenmcwilliams.kensocketchat.action;
    
    import com.opensymphony.xwork2.ActionSupport;
    
    public class Bomb extends ActionSupport{
        @Override
        public String execute() throws Exception{
            throw new RuntimeException();
        }
    }
    

    0 讨论(0)
提交回复
热议问题