In this article, I am going to discuss, how to catch Exception while you are using @Async annotation with Spring boot. Before deep diving to Exception handler I hope everyone who is reading this article, read my first part, If not I encourage you to do so, here is the link.
While you are forking thread from the main thread possibly you have two options.
1. Fire and forget :: you just fork a thread , assign some work to that thread, and just forget, at this moment, you do not bother with the outcome as you do not need this information in order to execute next business logic, generally it's return type is void, let's understand with an example, Say you are in a process of sending salary to the employees, as a part of that you send an email to each employee attaching respective salary slip, and you do it asynchronously. Obviously sending salary slip via email to the employee is not a part of your core business logic, it is a cross-cutting concern, it is a good to have a feature(Some cases it is must have, then you adopt retrying, or schedule mechanism) rather than must to have.
2. Fire with Callback:: Here you fork a thread from the main thread and assign some work to that thread then attach a 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 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 hold Employees general data (name, birthday, sex, address) and financial service holds(Salary, Tax, PF related data), so you fork two threads parallelly one for general service one for financial service, but you need both data to proceed further as in the report you need to combine both the data. So in the main thread, you want those results as a callback from subthreads, generally, we do it by CompletebleFuture(read Callable with Future).
In the above scenarios, if all is well that is the ideal case, but in the real-time exception can happen, then how you will handle Exception in the above two scenarios?
In the second scenario, It is very easy as result comes as a callback, whatever the result it is(Success or Failure), in case of failure, Exception wrapped inside CompltebleFuture you can check the same and handle it in the main thread. Not a big deal, basic java code. So I will skip that.
But Scenario one is tricky, you fork a thread with some business case, how you can be sure that is a success, or if that is failure how you will debug it, how you will get a trace that something goes wrong?
The solution is very 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 handles what to do with that, very Simple isn't it.
To achieve that we need to follow below steps.
1. AsyncConfigurer:: AsyncConfigurere is an Interface provided by Spring, It provides two methods one is if you want to override the TaskExecutor(Threadpool) another is an Exception handler where you can inject your exception handler so it can catch the uncaught exceptions. You can create your own class and implements that one directly. but I will not do that, as an alternative, I will use Spring 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;
@Configuration
@EnableAsync
public class CustomConfiguration extends AsyncConfigurerSupport {
@Override
public Executor getAsyncExecutor() {
return new SimpleAsyncTaskExecutor();
}
@Override
@Nullable
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, getAsyncExecutor method, I am not going to create any new Executor as I do not want to use my own task executor so I use Spring default SimpleAsyncExecutor.
But I need my custom uncaught exception handler to handle any uncaught Exception so I create a lambda expression which actually extends AsyncUncaughtExceptionHandler class and overrides handleuncaughtexception method.
In this way, I instruct Spring while loading, use my application specific AsyncConfugurer(CustomConfiguration) and use my 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;
@Component
public class AsyncMailTrigger {
@Async
public void senMailwithException() throws Exception{
throw new Exception("SMTP Server not found :: orginated from Thread :: " + Thread.currentThread().getName());
}
}
Now, 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;
@Component
public class AsyncCaller {
@Autowired
AsyncMailTrigger asyncMailTriggerObject;
public void rightWayToCall() throws Exception {
System.out.println("Calling From rightWayToCall Thread " + Thread.currentThread().getName());
asyncMailTriggerObject.senMailwithException();
}
}
Now let's run this Application using Spring boot, to see How it catch 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;
@SpringBootApplication
public class DemoApplication {
@Autowired
AsyncCaller caller;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return args -> {
caller.rightWayToCall();
};
}
}
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
Conclusion: Hope you like the tutorial, If you have a question please put it in the comment box and stay tuned for part 3.
While you are forking thread from the main thread possibly you have two options.
1. Fire and forget :: you just fork a thread , assign some work to that thread, and just forget, at this moment, you do not bother with the outcome as you do not need this information in order to execute next business logic, generally it's return type is void, let's understand with an example, Say you are in a process of sending salary to the employees, as a part of that you send an email to each employee attaching respective salary slip, and you do it asynchronously. Obviously sending salary slip via email to the employee is not a part of your core business logic, it is a cross-cutting concern, it is a good to have a feature(Some cases it is must have, then you adopt retrying, or schedule mechanism) rather than must to have.
2. Fire with Callback:: Here you fork a thread from the main thread and assign some work to that thread then attach a 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 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 hold Employees general data (name, birthday, sex, address) and financial service holds(Salary, Tax, PF related data), so you fork two threads parallelly one for general service one for financial service, but you need both data to proceed further as in the report you need to combine both the data. So in the main thread, you want those results as a callback from subthreads, generally, we do it by CompletebleFuture(read Callable with Future).
In the above scenarios, if all is well that is the ideal case, but in the real-time exception can happen, then how you will handle Exception in the above two scenarios?
In the second scenario, It is very easy as result comes as a callback, whatever the result it is(Success or Failure), in case of failure, Exception wrapped inside CompltebleFuture you can check the same and handle it in the main thread. Not a big deal, basic java code. So I will skip that.
But Scenario one is tricky, you fork a thread with some business case, how you can be sure that is a success, or if that is failure how you will debug it, how you will get a trace that something goes wrong?
The solution is very 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 handles what to do with that, very Simple isn't it.
To achieve that we need to follow below steps.
1. AsyncConfigurer:: AsyncConfigurere is an Interface provided by Spring, It provides two methods one is if you want to override the TaskExecutor(Threadpool) another is an Exception handler where you can inject your exception handler so it can catch the uncaught exceptions. You can create your own class and implements that one directly. but I will not do that, as an alternative, I will use Spring 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;
@Configuration
@EnableAsync
public class CustomConfiguration extends AsyncConfigurerSupport {
@Override
public Executor getAsyncExecutor() {
return new SimpleAsyncTaskExecutor();
}
@Override
@Nullable
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, getAsyncExecutor method, I am not going to create any new Executor as I do not want to use my own task executor so I use Spring default SimpleAsyncExecutor.
But I need my custom uncaught exception handler to handle any uncaught Exception so I create a lambda expression which actually extends AsyncUncaughtExceptionHandler class and overrides handleuncaughtexception method.
In this way, I instruct Spring while loading, use my application specific AsyncConfugurer(CustomConfiguration) and use my 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;
@Component
public class AsyncMailTrigger {
@Async
public void senMailwithException() throws Exception{
throw new Exception("SMTP Server not found :: orginated from Thread :: " + Thread.currentThread().getName());
}
}
Now, 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;
@Component
public class AsyncCaller {
@Autowired
AsyncMailTrigger asyncMailTriggerObject;
public void rightWayToCall() throws Exception {
System.out.println("Calling From rightWayToCall Thread " + Thread.currentThread().getName());
asyncMailTriggerObject.senMailwithException();
}
}
Now let's run this Application using Spring boot, to see How it catch 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;
@SpringBootApplication
public class DemoApplication {
@Autowired
AsyncCaller caller;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return args -> {
caller.rightWayToCall();
};
}
}
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
Conclusion: Hope you like the tutorial, If you have a question please put it in the comment box and stay tuned for part 3.