DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
What's in store for DevOps in 2023? Hear from the experts in our "DZone 2023 Preview: DevOps Edition" on Fri, Jan 27!
Save your seat
  1. DZone
  2. Coding
  3. Frameworks
  4. Effective Advice on Spring Async (ExceptionHandler): Part 2

Effective Advice on Spring Async (ExceptionHandler): Part 2

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

Shamik Mitra user avatar by
Shamik Mitra
·
Mar. 28, 19 · Tutorial
Like (7)
Save
Tweet
Share
38.99K Views

Join the DZone community and get the full member experience.

Join For Free

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. AsyncConfigurer: AsyncConfigurere 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;


@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 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;

@Component
public class AsyncMailTrigger {


@Async
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;

@Component

public class AsyncCaller {



@Autowired

AsyncMailTrigger asyncMailTriggerObject;



public void rightWayToCall() throws Exception {

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

asyncMailTriggerObject.senMailwithException();



}



}


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;



@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 liked this tutorial! If you have any questions, please drop them in the comments section below. And stay tuned for part three!

Spring Framework Advice (programming)

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

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Unleashing the Power of JavaScript Modules: A Beginner’s Guide
  • Why Does DevOps Recommend Shift-Left Testing Principles?
  • Leaders Make Their Own Problems
  • Integration: Data, Security, Challenges, and Best Solutions

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: