You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Spring调用方法中捕获@Async异步方法抛出的异常

Spring @Async异步方法异常捕获与REST响应实现

适用场景

  • Controller层调用TestService中被Spring @Async注解标注的异步方法getGood(String s)
  • 当方法入参不等于"good"时,异步方法主动抛出异常
  • Controller捕获到异步异常后,REST接口返回500内部服务器错误状态码
  • 基于CompletableFuture实现异步结果与异常的统一处理

完整实现代码

1. 异步配置类

首先需要在项目中开启Spring异步支持:

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;

@Configuration
@EnableAsync
public class AsyncConfiguration {
    // 可根据业务需要自定义异步线程池参数
}

2. 异步Service实现

异步方法返回类型指定为CompletableFuture,方便上层获取执行结果与异常:

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.util.concurrent.CompletableFuture;

@Service
public class TestService {

    @Async
    public CompletableFuture<String> getGood(String param) {
        if (!"good".equals(param)) {
            // 入参不符合要求时抛出异常
            throw new IllegalArgumentException("非法参数,仅允许传入\"good\"");
        }
        // 正常业务逻辑执行完成后返回结果
        return CompletableFuture.completedFuture("执行成功,参数:" + param);
    }
}

3. Controller层异常捕获处理

调用异步方法后阻塞获取结果,同时捕获异步执行抛出的异常,根据结果返回对应响应状态:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@RestController
public class TestController {

    @Autowired
    private TestService testService;

    @GetMapping("/test-async")
    public ResponseEntity<String> testAsyncMethod(@RequestParam String param) {
        CompletableFuture<String> asyncResult = testService.getGood(param);
        try {
            // 阻塞等待异步方法执行完成,获取返回结果
            String result = asyncResult.get();
            return ResponseEntity.ok(result);
        } catch (InterruptedException | ExecutionException e) {
            // 捕获异步方法抛出的业务异常,返回500状态码
            String errorMsg = e.getCause() != null ? e.getCause().getMessage() : "服务内部错误";
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorMsg);
        }
    }
}

验证逻辑

  • 调用接口传入参数param=good时,返回200状态码与成功提示
  • 调用接口传入其他参数时,返回500状态码与对应的错误信息

内容的提问来源于stack exchange,提问作者Janet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 00:24:00