在Feign调用接口时,如果遇到异常,可以通过自定义ErrorDecoder
来获取异常信息并抛出自定义异常。以下是具体的步骤和代码示例:
- 定义自定义异常:首先,你需要定义一个自定义异常类,用于封装异常信息。
public class CustomException extends RuntimeException {
private String errorCode;
private String message;
public CustomException(String errorCode, String message) {
super(message);
this.errorCode = errorCode;
this.message = message;
}
public String getErrorCode() {
return errorCode;
}
public String getMessage() {
return message;
}
}
- 实现Feign的
ErrorDecoder
接口:创建一个类实现ErrorDecoder
接口,并在decode
方法中解析异常信息,提取errorCode
,并抛出自定义异常。
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import com.fasterxml.jackson.databind.ObjectMapper;
public class CustomErrorDecoder implements ErrorDecoder {
private final ErrorDecoder defaultErrorDecoder = new Default();
@Override
public Exception decode(String methodKey, Response response) {
try {
String json = Util.toString(response.body().asReader());
ObjectMapper mapper = new ObjectMapper();
JsonNode errorNode = mapper.readTree(json).path("error");
if (errorNode.isMissingNode()) {
return defaultErrorDecoder.decode(methodKey, response);
}
String errorCode = errorNode.path("errorCode").asText();
String message = errorNode.path("message").asText();
return new CustomException(errorCode, message);
} catch (IOException e) {
return defaultErrorDecoder.decode(methodKey, response);
}
}
}
- 配置Feign客户端使用自定义
ErrorDecoder
:在你的Feign客户端配置中指定使用自定义的ErrorDecoder
。
import org.springframework.context.annotation.Bean;
public class FeignConfig {
@Bean
public ErrorDecoder errorDecoder() {
return new CustomErrorDecoder();
}
}
- 使用Feign客户端:在你的服务中使用Feign客户端,并处理可能抛出的自定义异常。
@FeignClient(name = "auditApplicationApi", configuration = FeignConfig.class)
public interface AuditApplicationApi {
@PostMapping("/audit-applications")
String create(CreateAuditApplicationDto dto);
}
public class AuditApplicationService {
public void createAuditApplication(CreateAuditApplicationDto dto) {
try {
AuditApplicationApi api = Feign.builder().target(AuditApplicationApi.class);
api.create(dto);
} catch (CustomException e) {
// 处理自定义异常
System.out.println("Error code: " + e.getErrorCode());
System.out.println("Error message: " + e.getMessage());
throw e;
}
}
}
通过上述步骤,你可以在Feign调用接口时捕获异常信息,并根据异常信息抛出自定义异常。这样就可以在调用方获取到服务端抛出的自定义错误码,并进行相应的异常处理。