1

In Struts 2:

in case of exception in prepare method, the Action is not called.

How to handle Exception in prepare() method so that action method is always called ?

Now I'm doing this but surely exists a better way:

       private Exception exceptionInPrepare = null;
        
        @Override
        public void prepare() throws Exception {
            try {
             ...
             ...
            } catch (Exception e) {
                exceptionInPrepare = e;
            } 
        }
        
       @Action("myMethod")
       public String myMethod() {
                
            try {
            
                if (exceptionInPrepare != null) {
                    throw exceptionInPrepare;
                }
                 ...
                 ...            
            } catch (Exception e) {
                ...
                ...
            } finally {
               ...
               ...
            }
    
            return ....
        }
    
Roman C
  • 49,761
  • 33
  • 66
  • 176
Lof
  • 251
  • 1
  • 3
  • 7
  • This is probably the quickest solution--it's not a *terrible* way to do it, but without context (e.g., what kind of exception are you trying to "ignore until later") or reasoning behind subverting the default S2 flow, it's difficult to say what the "best" way to do it would be. – Dave Newton May 23 '21 at 16:35

1 Answers1

0

The method signature according to the documentation for Preparable interface is

void prepare()
     throws Exception

This method is called to allow the action to prepare itself.

Throws:

Exception - thrown if a system level exception occurs.

So you could throw an exception in the prepare() method.

You shouldn't call action if exception is thrown in prepare method. It should be handled by the global exception handler. See this answer for more details.

Roman C
  • 49,761
  • 33
  • 66
  • 176
  • I tried both ways: with "throws Exception" and without and the problem don't change: when an exception raise in prepare the action is not called. – Lof May 24 '21 at 12:27
  • You shouldn't call action if exception is thrown in prepare method. It should be handled by the global exception handler. – Roman C May 25 '21 at 20:30
  • Yes but the exception happens in the Action. The prepare method is in the Action class, so I think correct the exception should be handled by Action itself. I can't find any reference in Struts 2 docs about this behaviour... – Lof May 30 '21 at 05:05
  • Not all exceptions are handled by the action. But there's an exception interceptor on bottom of the stack which is capable to catch exceptions. – Roman C Aug 17 '21 at 08:38