【问题标题】:Exception handling for Spring Boot @Async methodsSpring Boot @Async 方法的异常处理
【发布时间】:2020-11-27 10:48:48
【问题描述】:

我对 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


【解决方案1】:

如何将@Async 移到较低级别,所以只有

javaMailSender.send(mimeMessage);

会以异步方式调用吗?

使用包装javaMailSender的公共异步方法将其提取到不同的bean,并从sendMessage的方法中删除异步

【讨论】:

    猜你喜欢
    • 2018-11-07
    • 1970-01-01
    • 2023-03-28
    • 2016-11-10
    • 2015-02-23
    • 2016-09-29
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    相关资源
    最近更新 更多