步骤 1: 添加 Feign 依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
步骤 2: 创建自定义错误解码器
注意: 可以在decode方法抛出业务异常,返回信息从response body获取
import feign.Response;
import feign.codec.ErrorDecoder;
import feign.Util;
import java.io.IOException;
import org.springframework.http.HttpStatus;
public class CustomErrorDecoder implements ErrorDecoder {
@Override
public Exception decode(String methodKey, Response response) {
String body = "";
try {
if (response.body() != null) {
body = Util.toString(response.body().asReader());
}
} catch (IOException e) {
// 处理读取响应体时的异常
e.printStackTrace();
}
HttpStatus status = HttpStatus.valueOf(response.status());
switch (status) {
case BAD_REQUEST:
return new BadRequestException("Bad request error: " + body);
case NOT_FOUND:
return new NotFoundException("Resource not found: " + body);
case INTERNAL_SERVER_ERROR:
return new InternalServerErrorException("Internal server error: " + body);
default:
return new GeneralFeignException("General error: " + body, response.status());
}
}
// 自定义异常类
public static class BadRequestException extends RuntimeException {
public BadRequestException(String message) {
super(message);
}
}
public static class NotFoundException extends RuntimeException {
public NotFoundException(String message) {
super(message);
}
}
public static class InternalServerErrorException extends RuntimeException {
public InternalServerErrorException(String message) {
super(message);
}
}
public static class GeneralFeignException extends RuntimeException {
private final int status;
public GeneralFeignException(String message, int status) {
super(message);
this.status = status;
}
public int getStatus() {
return status;
}
}
}
步骤 3: 配置 Feign 使用自定义错误解码器
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FeignConfig {
@Bean
public ErrorDecoder errorDecoder() {
return new CustomErrorDecoder();
}
}
步骤 4: 创建 Feign 客户端接口
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
@FeignClient(name = "exampleClient", url = "https://api.example.com", configuration = FeignConfig.class)
public interface ExampleClient {
@GetMapping("/data")
String getData();
}