/**
* <p>
* 解决Feign的异常包装,统一返回结果
* </p>
*
* @author dingjm
* @since 2023/2/2
*/
public class OpenFeignErrorDecoder implements ErrorDecoder {
/**
* Feign异常解析
*
* @param methodKey 方法名
* @param response 响应体
* @return BizException
*/
@Override
public Exception decode(String methodKey, Response response) {
try {
/*Logger / System.out.println / IDE 调试模式
在获得response.body()之前不要使用上述任何功能
如果您使用上述任何功能打印/记录/查看您的response 对象,那么它将在内部处理response.body() 并关闭InputStream。所以在这种情况下你会得到Stream is closed 错误。
要解决此问题,请在记录器之前处理 response.body()。现在您可以通过运行您的应用程序而不是在调试模式下来检查这一点。*/
//获取数据
String body = Util.toString(response.body().asReader(Charset.defaultCharset()));
MsgResult resultData = JSON.parseObject(body, MsgResult.class);
if (!resultData.getSuccess()) {
return new GlobalException(resultData.getMsg());
}
} catch (IOException e) {
e.printStackTrace();
}
return new GlobalException(String.format("Feign client 调用%d异常", methodKey));
}
}
@ConditionalOnClass(Feign.class)
@Configuration
public class OpenFeignConfig {
/**
* 自定义异常解码器
*
* @return OpenFeignErrorDecoder
*/
@Bean
public ErrorDecoder errorDecoder() {
return new OpenFeignErrorDecoder();
}
}