首页 > 解决方案 > 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();
    }
}

标签: springspring-bootasynchronous

解决方案


@Async将其移至较低级别怎么样,所以只有

javaMailSender.send(mimeMessage);

会以异步方式调用吗?

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


推荐阅读