【发布时间】: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();
}
}
【问题讨论】:
-
也许这篇文章能提供一些帮助dzone.com/articles/spring-async-and-exception
标签: spring spring-boot asynchronous