目录FeignClient服务器抛出异常客户端处理feign异常拦截器FeignClient异常合集Mark问题1问题2FeignClient服务器抛出异常客户端处理 在使用feig
在使用feign进行远程方法调用时,如果远程服务端方法出现异常,客户端有时需要捕获,并且把异常信息返回给前端,而如果在开启熔断之后,这个异常会被消化,所以说,如果希望拿到服务端异常,
feign.hystrix.enable需要设置为false,而当不开熔断时,我们也有几种方法把拿到服务端的异常信息,下面总结一下。
注册一个Bean对象,当feign调用出现异常的时候,会触发这个方法:
import com.test.JSONUtils;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import io.test.BadRequestException;
import io.test.InternalServerErrorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static feign.FeignException.errorStatus;
@Configuration
public class FeignClientErrorDecoder implements ErrorDecoder {
private Logger logger = LoggerFactory.getLogger(FeignClientErrorDecoder.class);
@Override
public Exception decode(String methodKey, Response response) {
Map<String, Object> jsonBody = new HashMap<>();
jsonBody.put("message", "Internal server error");
try {
String body = Util.toString(response.body().asReader());
jsonBody = JsonUtils.toMap(body);
} catch (IOException e) {
logger.error("feign.IOException", e);
}
assert jsonBody != null;
if (response.status() >= 400 && response.status() < 500) {
throw new BadRequestException(jsonBody.get("message").toString());
}
if (response.status() >= 500) {
throw new InternalServerErrorException(jsonBody.get("message").toString());
}
return errorStatus(methodKey, response);
}
}
注意,使用这个方式,需要在熔断器关闭时才起作用,因为它们的执行过程是,先走这个拦截器,再走熔断的fallback,所以这个异常会被熔断吞掉,返回状态为200,返回值为你的fallback的默认值。
feignClient调用报异常cause:Content-Type cannot contain wildcard type ‘*’
是因为远程调用的时候入参识别不了application/json
解决办法:在方法上加上类型即可consumes = MediaType.APPLICATION_JSON_VALUE
@RequestMapping(value = "/xxx/xxx/xxx/xxx/xxx/xxx/result",method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON_VALUE)
ResponseResult xxx(TaskParam taskParam);
fallback 与fallbackFactory的使用
fallbackFactory:抛出异常可查看,一般看里面抛出的异常日志即可判断远程调用的问题所在。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。
--结束END--
本文标题: FeignClient服务器抛出异常客户端处理方案
本文链接: https://www.lsjlt.com/news/151657.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-05-13
2024-05-13
2024-05-11
2024-05-11
2024-05-10
2024-05-07
2024-04-30
2024-04-30
2024-04-30
2024-04-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0