在 Java 中,“捕获 API 接口异常”通常可以从代码层(try-catch)、框架层(全局异常处理)、网关/代理层三个维度来做。下面按常见场景给你一个系统性的说明。
适用于具体方法级别的异常捕获。
@RestController
@RequestMapping("/api")
public class UserController {
@GetMapping("/user/{id}")
public User getUser(@PathVariable Long id) {
try {
return userService.findById(id);
} catch (UserNotFoundException e) {
throw new ResponseStatusException(
HttpStatus.NOT_FOUND, "用户不存在", e);
} catch (Exception e) {
throw new ResponseStatusException(
HttpStatus.INTERNAL_SERVER_ERROR, "系统异常", e);
}
}
}
✅ 优点:直观
❌ 缺点:重复代码多,不适合大型项目
最适合 RESTful API
public class ApiResult<T> {
private int code;
private String message;
private T data;
// getter/setter/构造方法
}
@RestControllerAdvice
public class GlobalExceptionHandler {
// 捕获自定义业务异常
@ExceptionHandler(BusinessException.class)
public ApiResult<Void> handleBusiness(BusinessException e) {
return new ApiResult<>(e.getCode(), e.getMessage(), null);
}
// 捕获参数校验异常
@ExceptionHandler(MethodArgumentNotValidException.class)
public ApiResult<Void> handleValid(MethodArgumentNotValidException e) {
String msg = e.getBindingResult()
.getFieldError()
.getDefaultMessage();
return new ApiResult<>(400, msg, null);
}
// 捕获所有未处理异常
@ExceptionHandler(Exception.class)
public ApiResult<Void> handleAll(Exception e) {
e.printStackTrace();
return new ApiResult<>(500, "系统异常", null);
}
}
✅ 优点:
如果你希望在 Controller 之前或之后统一捕获:
@Component
public class ApiExceptionFilter implements Filter {
@Override
public void doFilter(ServletRequest req,
ServletResponse res,
FilterChain chain) throws IOException {
try {
chain.doFilter(req, res);
} catch (Exception e) {
// 统一写响应
}
}
}
✅ 适合:
如果你是调用别人 API:
try {
restTemplate.getForObject(url, String.class);
} catch (HttpClientErrorException e) {
// 4xx
} catch (HttpServerErrorException e) {
// 5xx
} catch (ResourceAccessException e) {
// 超时 / 网络异常
}
或使用 WebClient(响应式):
webClient.get()
.uri(url)
.retrieve()
.onStatus(HttpStatus::isError,
resp -> Mono.error(new ApiException("调用失败")))
.bodyToMono(String.class)
.block();
CompletableFuture.supplyAsync(() -> {
throw new RuntimeException("error");
}).exceptionally(ex -> {
log.error("异步异常", ex);
return null;
});
✅ 推荐组合方案
@RestControllerAdvice❌ 避免:
Throwable如果你能说明:
我可以给你更精准的示例代码。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。