如下代码为我们框架中自己开发的Decoder:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
@Slf4j
public class FeignDecoder extends SpringDecoder {
public FeignDecoder(ObjectFactory<HttpMessageConverters> messageConverters) {
super(messageConverters);
}
@Override
public Object decode(final Response response, Type type) throws IOException, FeignException {
Object result = super.decode(response, type);
if(Objects.nonNull(result)){
if (result.getClass() == ResponseVo.class) {
ResponseVo vo = (ResponseVo) result;
if (vo.getCode() != HttpStatus.OK.value()) {
log.info(String.format("Feign calling fail [%s] : %s",
response.headers().get(APICons.TRACKING_CODE),
JSONObject.toJSONString(vo)));
throw new FeignCallException(vo);
}
}
}
return result;
}
}
|
这个Decoder增加了一些我们默认的行为:如果我们client的返回结果为ResponseVo,则我们需要判断我们的code值是否为HttpStatus.OK,如果不是的话,则抛出异常。我肯定是不喜欢这种写法的,因为这不是FeighCallException的默认行为,会让人很疑惑。而且,如果我们想将服务提供端的错误消息抛出去,则我们需要用如下的写法:
1
2
3
4
5
6
7
8
9
10
11
12
|
ResponseVo<Void> response = null;
try {
response = inviteForMaterialPlatformClient.commitInviteData(request);
} catch (DecodeException e) {
if (e.getCause() instanceof FeignCallException) {
//noinspection unchecked
response = ((FeignCallException) e.getCause()).getResponse();
}
}
|