0

I'm writing a custom AOP method-handler and I have two methods with different annotations:

@AfterReturning(value = "@annotation(Metric)", returning = "response")
public void afterReturning(JoinPoint joinPoint, ResponseWithStatus response) {
    final Signature signature = joinPoint.getSignature();
    final int responseStatus = response.getStatus();
    metrics.putIfAbsent(signature, resultCounters);
    if (responseStatus == ResponseStatus.SUCCESS.getValue()) {
        System.out.println("Method " + signature + " returned its result");
        metrics.get(signature).get(SUCCESS).increment();
    } else if (errorCodes.contains(responseStatus)) {
        System.out.println("Method " + signature + " returned error");
        metrics.get(signature).get(ERROR).increment();
    } else if (businessErrorCodes.contains(responseStatus)) {
        System.out.println("Method " + signature + " returned business error");
        metrics.get(signature).get(BUSINESS_ERROR).increment();
    }
}

@AfterThrowing(value = "@annotation(Metric)", throwing = "exception")
public void afterThrowing(JoinPoint joinPoint, Exception exception) {
    final Signature signature = joinPoint.getSignature();
    final Class<? extends Exception> exceptionClass = exception.getClass();
    final String exceptionName = exceptionClass.getName();
    metrics.putIfAbsent(signature, resultCounters);
    if (exceptionClass.equals(ValidationWebFault_Exception.class)) {
        System.out.println("Method " + signature + " threw " + exceptionName);
        metrics.get(signature).get(ERROR).increment();
    }
}

But my methods are being handled only by @AfterThrowing method. How I can use both of them for ONE annotation?

Maksym Rybalkin
  • 453
  • 1
  • 8
  • 22
  • 1
    To understand, the method is not advised when method returns successfully? An alternative is to use an @Around advice and handle based on return / exception – R.G May 26 '20 at 16:49
  • @R.G Yes, it works only with throwing an Exception. But I need different logic after success and an exception – Maksym Rybalkin May 26 '20 at 16:54
  • 2
    Do check the return type mismatch if any . @Around can be used execute two different logic on successful return and exception using a try catch block . A sample format can be found in this [answer](https://stackoverflow.com/a/61765084/4214241) – R.G May 26 '20 at 17:01

1 Answers1

0

I've resolved the problem by myself. I just need to use Object response instead of ResponseWithStatus response in my afterReturning() method

Maksym Rybalkin
  • 453
  • 1
  • 8
  • 22
  • 1
    `ResponseWithStatus response` is fine if (and only if) all your intercepted methods also return that type or any of its subtypes. `Object` could be overkill if you can be more specific in your matching type expression. But your expected return type probably was just something else. – kriegaex May 27 '20 at 08:48