Spring Boot @Async 方法的异常处理

问题描述 投票:0回答:2

我对 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();
    }
}
spring spring-boot asynchronous
2个回答
1
投票

如何将

@Async
移动到较低的级别,这样就只有

 javaMailSender.send(mimeMessage);

会以异步方式调用吗?

使用包装

javaMailSender
的公共异步方法将其提取到不同的 bean,并从
sendMessage

的方法中删除异步

0
投票

您可以尝试使用 GlobalAsyncExceptionalHandler 来代替 GlobalExceptionHandler 吗?请参考以下内容

https://jhamukul007.medium.com/how-to-caught-async-exception-spring-boot-application-168126214deb

© www.soinside.com 2019 - 2024. All rights reserved.