spring - Spring Boot @Async 方法的异常处理
问题描述
我对 Spring Boot 很陌生。在一个项目中,我想异步发送一封电子邮件。下面,你可以看到我到目前为止所拥有的。
我遇到的问题如下:外部系统向控制器发送 POST 请求。如果在构建或发送邮件时发生异常,则GlobalExceptionHandler
不会调用。因此,控制器总是返回 HTTP 201,因此调用者假设一切正常。
我如何将我的异常处理程序与@ControllerAdvice
此类异步方法集成?
控制器
@PostMapping(value = "/mail", consumes = MediaType.APPLICATION_JSON_VALUE)
public void send(@Validated @RequestBody EmailNotificationRequest emailNotificationRequest) throws MessagingException {
emailService.sendMessage(emailNotificationRequest);
}
服务
@Async
public void sendMessage(EmailNotificationRequest emailNotificationRequest) throws MessagingException {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
// build the message
javaMailSender.send(mimeMessage);
}
异常处理程序
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler extends AbstractExceptionHandler {
/**
* Handles any exception which is not handled by a specific {@link ExceptionHandler}.
*/
@ExceptionHandler(value = {Throwable.class})
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ApplicationResponse handleThrowable(Throwable ex) {
log.error("An unhandled error occurred: {}", ex.getMessage());
return buildErrorResponse();
}
}
解决方案
@Async
将其移至较低级别怎么样,所以只有
javaMailSender.send(mimeMessage);
会以异步方式调用吗?
使用公共异步方法将其提取到不同的 bean,该方法包装javaMailSender
并从方法中删除异步sendMessage
推荐阅读
- python - 在 PyQt5 中获取滚动条拇指的大小/宽度?
- c++11 - __int64' 后跟 'int64' 是非法的
- dart - Flutter 获取列表值到另一个列表
- javascript - 如何使用 jQuery 和 Bootstrap 在文档中创建多个模式?
- micronaut - Micronaut Swagger Groovy 不生成 openapi yaml 文件
- python - 如何比较熊猫中两个相关数据框的两列
- android - 如何在不从 Android 应用程序中获取视频数据的情况下安全地解密 Android 中的视频数据
- javascript - React Native 与 react-navigation 和 Redux - 如何实现全局可用的“退出”按钮
- python - 在 Pandas 数据帧之间乘以多个因素的最有效方法是什么?
- javascript - ssh2-sftp-client 获取多个文件 - 错误“结束后写入”