How to re-throw exception in AspectJ around advise

后端 未结 3 1334
孤城傲影
孤城傲影 2021-02-09 10:19

I have some methods which throws some exception, and I want to use AspectJ around advise to calculate the execution time and if some exception is thrown and to log into error lo

3条回答
  •  遇见更好的自我
    2021-02-09 10:40

    There is an "ugly" workaround - I found them in Spring4 AbstractTransactionAspect

    Object around(...): ... {
        try {
            return proceed(...);
        }
        catch (RuntimeException ex) {
            throw ex;
        }
        catch (Error err) {
            throw err;
        }
        catch (Throwable thr) {
            Rethrower.rethrow(thr);
            throw new IllegalStateException("Should never get here", thr);
        }
    }
    
    /**
     * Ugly but safe workaround: We need to be able to propagate checked exceptions,
     * despite AspectJ around advice supporting specifically declared exceptions only.
     */
    private static class Rethrower {
    
        public static void rethrow(final Throwable exception) {
            class CheckedExceptionRethrower {
                @SuppressWarnings("unchecked")
                private void rethrow(Throwable exception) throws T {
                    throw (T) exception;
                }
            }
            new CheckedExceptionRethrower().rethrow(exception);
        }
    }
    

提交回复
热议问题