使用 @restcontrolleradvice 结合 @exceptionhandler 可以统一捕获远程调用抛出的异常。核心做法是识别远程调用框架(如 feign、resttemplate)抛出的特定异常类型,在 advice 类中定义对应的处理方法并返回标准化的错误响应对象。

FeignClient 默认抛出什么异常
FeignClient 在远程调用失败时,默认会抛出 feign.FeignException 及其子类。具体包括连接超时导致的 feign.RetryableException 和 HTTP 状态码非 2xx 导致的 feign.FeignException$StatusCodeException。这些异常都继承自 RuntimeException,因此可以在全局异常处理器中被捕获。

import feign.FeignException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(FeignException.class)
public String handleFeign(FeignException e) {
return "Remote call failed: " + e.status();
}
}
RestTemplate 遇到网络错误返回什么
RestTemplate 在请求失败时会抛出 ResourceAccessException。这通常发生在网络连接被拒绝、连接超时或读取超时的情况下。该异常位于 org.springframework.web.client 包下,与 Feign 的异常体系完全独立,需要单独定义处理逻辑。

import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceAccessException.class)
public String handleRest(RestAccessException e) {
return "Network error: " + e.getMessage();
}
}
如何区分不同 HTTP 状态码的远程异常
在处理 FeignException 时,可以通过调用其 status() 方法获取具体的 HTTP 状态码。例如,404 表示资源未找到,500 表示服务端内部错误。根据状态码的不同,可以返回不同的业务提示或记录不同的日志级别,从而实现更精细的错误控制。











