Effective Advice on Spring Async (ExceptionHandler): Part 2

DZone 's Guide to

Effective Advice on Spring Async (ExceptionHandler): Part 2

Want exceptional exception handling? Look no further than Spring Boot and the Async annotation.

· Java Zone ·
Free Resource

In this article, I am going to discuss how to catch an exception while using the @Async annotation with Spring Boot. Before deep diving to exception handlers, I hope everyone who is reading this article read part one. If not, I encourage you to do so. Here is the link.

While you are forking thread from the main thread, you have two options:

1. Fire and forget: you just fork a thread, assign some work to that thread, and forget about it. At this moment, you do not need to bother with the outcome, as you do not need this information in order to execute your next business logic. Generally, it's return type is void. Let's better understand this with an example. Say you are in the process of sending a salary to employees. As a part of that, you send an email to each employee attaching respective salary slip, and you do it asynchronously. Obviously, sending a salary slip via email to the employee is not a part of your core business logic; it is a cross-cutting concern. However, it is a good feature to have. In some cases, it is a must-have. Then, you adopt retrying or schedule a mechanism.

2. Fire with Callback: Here, you fork a thread from the main thread, assign some work to that thread, and then attach Callback. After that, the main thread proceeds with other tasks, but the main thread keeps checking the Callback for the result. The main thread needs that outcome from the sub-thread as a form of callback to execute further.

Say you are preparing an employee report. Your software stores employee information in different backends based on the data category — say, General Service holds employees' general data (name, birthday, sex, address) and Financial Service holds the salary, tax, PF-related data, etc. So, you fork two threads parallelly — one for General Service and one for Financial Service. However, you need both sets of data to proceed in the report, as you need to combine the data. So, in the main thread, you want those results to appear as a callback from the subthreads. Generally, we do this by  CompletebleFuture(read Callable with Future).

In the above scenarios, if all is well, that is the ideal scenario. But when a real-time exception happens, how do you handle an exception in the above two scenarios?

In the second scenario, it is very easy, as the result comes as a callback and is either a success or failure. In the case of a failure, the exception is wrapped inside CompltebleFuture. You can check the same and handle it in the main thread. Not a big deal; this basic Java code. So, I will skip that.

But scenario one is tricky; you fork a thread with some business case. But how you can be sure that it is a success? Or if it is a failure, how will you debug it? How do you get a trace if something goes wrong?

The solution is simple. You need to inject your own exception handler so that if an exception occurs while you are executing an Async method, it should pass the control to that handler, and then, the handlers know what to do with that. Simple, isn't it?

To achieve that, we need to follow the steps below.

1. AsyncConfigurerAsyncConfigurere is an interface provided by Spring that provides two methods — one is if you want to override the TaskExecutor(Threadpool) and another is an exception handler. For the exception handler, you can inject it so that it catches the uncaught exceptions. You can create your own class that implements that one directly. But I will not do that in this example. As an alternative, I will use Spring's AsyncConfigurerSupport class, which annotates by @Configuration and @EnableAsync and provides a default implementation.

package com.example.ask2shamik.springAsync;

import java.lang.reflect.Method;

import java.util.concurrent.Executor;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.lang.Nullable;
import org.springframework.scheduling.annotation.AsyncConfigurerSupport;
import org.springframework.scheduling.annotation.EnableAsync;

public class CustomConfiguration extends AsyncConfigurerSupport {


public Executor getAsyncExecutor() {

return new SimpleAsyncTaskExecutor();




public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {

return (throwable, method, obj)->{

System.out.println("Exception Caught in Thread - " + Thread.currentThread().getName());

System.out.println("Exception message - " + throwable.getMessage());

System.out.println("Method name - " + method.getName());

for (Object param : obj) {

System.out.println("Parameter value - " + param);





Please note that, in case of a  getAsyncExecutor method, I am not going to create any new executors, as I do not want to use my own task executor. Therefore, I will use Spring's default SimpleAsyncExecutor.

But I need my custom uncaught exception handler to handle any uncaught exception, so I create a lambda expression that extends the AsyncUncaughtExceptionHandler class and overrides the  handleuncaughtexception method.

In this way, I instruct Spring while loading using my application-specific  AsyncConfugurer(CustomConfiguration) and lambda expression as an exception handler.

Now, I create an @Async method, which will throw an exception:

package com.example.ask2shamik.springAsync.demo;

import java.util.Map;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

public class AsyncMailTrigger {

public void senMailwithException() throws Exception{
throw new Exception("SMTP Server not found :: orginated from Thread :: " + Thread.currentThread().getName());



Now,  we create a caller method.

package com.example.ask2shamik.springAsync.demo;

import java.util.HashMap;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.scheduling.annotation.Async;

import org.springframework.stereotype.Component;


public class AsyncCaller {


AsyncMailTrigger asyncMailTriggerObject;

public void rightWayToCall() throws Exception {

System.out.println("Calling From rightWayToCall Thread " + Thread.currentThread().getName());




Next, let's run the application using Spring Boot to see how it catches the exception thrown by the method sendMailwithException.

package com.example.ask2shamik.springAsync;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.CommandLineRunner;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.context.ApplicationContext;

import org.springframework.context.annotation.Bean;

import org.springframework.scheduling.annotation.EnableAsync;

import com.example.ask2shamik.springAsync.demo.AsyncCaller;


public class DemoApplication {


AsyncCaller caller;

public static void main(String[] args) {

SpringApplication.run(DemoApplication.class, args);



public CommandLineRunner commandLineRunner(ApplicationContext ctx) {

return args -> {





And the output is:

Calling From rightWayToCall Thread main

Exception Caught in Thread - SimpleAsyncTaskExecutor-1

Exception message - SMTP Server not found:: originated from Thread:: SimpleAsyncTaskExecutor-1

Method name - senMailwithException


Hope you liked this tutorial! If you have any questions, please drop them in the comments section below. And stay tuned for part three!

annotations, async, exception handling, exceptionhandler, java, spring, spring boot, spring boot tutorial, spring framework, tutorial

Published at DZone with permission of Shamik Mitra , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}