英文:
How to handle @Async in Spring boot
问题
public class ServiceImpl {
@Autowired
EmailService emailService;
public void arr() throws Exception {
int[] arr = {1, 2, 3, 4};
for (int i = 0; i < arr.length + 1; i++) {
System.out.print(i + " ");
}
emailService.sendMail("邮件主题", "邮件正文", "xuz@gmail.com", "abc@gmail.com");
}
}
@EnableAsync
public class EmailService {
@Async
public void sendMail(String subject, String body, String from, String to) {
// 发送邮件功能的实现
}
}
我在邮件服务中使用了 @Async 注解来触发邮件发送。如果在调用方法中发生任何错误,邮件会被触发,而不考虑调用方法中的任何异常。
我不希望在调用方法发生错误后继续执行邮件发送方法。我该如何处理?
在上面的示例中,for 循环会抛出 ArrayIndexOutOfBoundException,即使出现异常,邮件也会被触发,因为它是一个异步函数。
我不希望在 arr() 方法中出现异常时触发邮件发送。
英文:
public class ServiceImpl{
@Autowired
EmailService emailService;
public void arr() throws Exception
{
int[] arr={1,2,3,4};
for(int i=0;i<arr.length+1;i++)
{
System.out.print(i+" ");
}
emailService.sendMail("Subject of mail","body of mail","xuz@gmail.com","abc@gmail.com");
}
}
@EnableAsync
public class EmailService {
@Async
public void sendMail(String subject,String body,String from,String to)
{
//Implementation of sendMail function
}
}
I have used @Async annotation in the email service for triggering the mail, if any error occurs in the caller method the mail is getting triggered irrespective of any exceptions in the caller method.
I don't want the email method to get executed after the error occurs in the caller method. how can i handle this?
In the above example the for loop throws arrayIndexOutOfBoundException even after the exception occurs the mail will get triggered since it is a async function .
I don't want the mail to get triggered if exception occurs in arr() method
专注分享java语言的经验与见解,让所有开发者获益!
评论