By default exceptions thrown in Spring boot 3.4 rest controllers are logged in the dispatcher. These can also be customized with @ControllerAdvice or even logged in servlet filters.
However if an exception is thrown and not explicitly caught in a kafka listener, aysnc @EventListener or Spring scheduler @Scheduled method, nothing is logged.
Is there some way to catch these?
By default exceptions thrown in Spring boot 3.4 rest controllers are logged in the dispatcher. These can also be customized with @ControllerAdvice or even logged in servlet filters.
However if an exception is thrown and not explicitly caught in a kafka listener, aysnc @EventListener or Spring scheduler @Scheduled method, nothing is logged.
Is there some way to catch these?
Share Improve this question asked Feb 14 at 14:40 John LittleJohn Little 12.4k26 gold badges111 silver badges183 bronze badges1 Answer
Reset to default 2I encountered a similar issue some time ago; a @Scheduled
bulk update event failed in the middle of the night but went unnoticed because there was no alert and it happened outside of working hours. I couldn't find a solution similar to ControllerAdvice for @Scheduled
events, so I decided to write a custom AOP advice to send out an alert. It looked similar to this (modified for your use-case):
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LogOnFailure {
/**
* The name of the operation to be used in the log messsage.
* If no operation name is given, the name of the method is used.
*/
String operationName() default "";
}
import .aspectj.lang.JoinPoint;
import .aspectj.lang.annotation.AfterThrowing;
import .aspectj.lang.annotation.Aspect;
import .aspectj.lang.reflect.MethodSignature;
@Component
@Aspect
@Order // default order is LOWEST_PRECEDENCE
public class LogOnFailureAspect {
private static final Logger log = LoggerFactory.getLogger(LogOnFailureAspect.class);
// java:S112: Define and throw a dedicated exception instead of using a generic one.
@SuppressWarnings("java:S112")
@AfterThrowing(value = "@annotation(com.package.LogOnFailure)", throwing = "e")
public void handleException(JoinPoint jp, Throwable e) throws Throwable {
var operationName = getOperationName(jp);
log.error("An exception occurred while processing {}", operationName, e);
throw e;
}
private String getOperationName(JoinPoint jp) {
var method = ((MethodSignature) jp.getSignature()).getMethod();
var operationName = method.getAnnotation(LogOnFailure.class).operationName();
return (operationName == null || operationName.isBlank()) ? method.getName() : operationName;
}
}
Usage:
@Scheduled(cron="xxx")
@LogOnFailure
public void scheduled() {
throw new RuntimeException("test");
}
I'm not sure if my setup also works in asynchronous situations (or consumer/supplier bean setups), because I didn't need it in such cases. It might be useful to test it more thoroughly in those scenarios.