Shannon
Shannon

Reputation: 1163

Spring @Async abstraction is leaky regarding exception handling

When using Spring's @Async annotation, the abstraction is leaky when it comes to (checked) exceptions in the throws clause of the method. The compiler will force the caller to handle the exception, but in actuality the caller will never see exceptions thrown by the @Async method. Instead, depending on the implementation, it will be handled & logged by Spring, or given to a user-configured exception handler, or produced when Future#get() is called on the return value.

Therefore, I am forming the opinion that @Async methods should, as a rule, never throw checked exceptions. Instead, they should wrap all checked exceptions in types of RuntimeException so that no throws clause is present.

Is this an accurate evaluation? Is there any tooling or programming approach that fixes the leak? Does anybody happen to know what the Spring developers think of this, or if there are any plans to improve the situation? Thanks!

Possibly related: Spring Async method hides exceptions

Upvotes: 7

Views: 992

Answers (1)

Jukka
Jukka

Reputation: 4663

Your evaluation is probably correct.

Now, if you want to handle the said exception, just do this:

@Async
void mangle() {
    try {
        doMangle();
    } catch (YourCheckedException e) {
        // Handle it
    }
}

void doMangle() throws YourCheckedException {
    ...
}

Upvotes: 2

Related Questions