feign client遠(yuǎn)程調(diào)用時(shí),如果遇到返回的http status不是200的情況,則會(huì)拋出異常
feign.FeignException。但是這種異常不方便處理,所以最好還是根據(jù)錯(cuò)誤信息拋出自定義異常
拋出自定義異常
- 自定義異常
public class HwException extends RuntimeException {
public HwException(String message) {
super(message);
}
}
- 定義ErrorDecoder
public class HwNetApiErrorDecoder implements ErrorDecoder {
final ObjectMapper mapper;
public HwNetApiErrorDecoder(ObjectMapper mapper) {
this.mapper = mapper;
}
@Override
public Exception decode(String methodKey, Response response) {
if (HttpStatus.OK.value() == response.status()) {
//這里不應(yīng)該出現(xiàn),因?yàn)橹挥胁皇?00的返回結(jié)果,才是錯(cuò)誤
FeignException exception = errorStatus(methodKey, response);
throw new RuntimeException(exception);
}
try {
HwNetResult<?> netRet = mapper.readValue(response.body().asInputStream(), HwNetResult.class);
if (netRet.isSuccess()) {
throw new RuntimeException("return values is success but http status is not 200");
}
throw new HwException(netRet.getErrorCode());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
- Feign自定義配置:
public class WxFeignConfiguration {
@Bean
public HwNetApiErrorDecoder hwNetApiErrorDecoder(ObjectMapper mapper) {
return new HwNetApiErrorDecoder(mapper);
}
}
效果
- 當(dāng)http請(qǐng)求返回400錯(cuò)誤時(shí),并且error_code="one_IE"時(shí),則會(huì)拋出異常
HwException: one_IE
java.lang.IllegalStateException: Failed to execute ApplicationRunner
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:762)
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:749)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:314)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1303)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1292)
at com.wx.demo.server.WxkjDemoServerApplication.main(WxkjDemoServerApplication.java:34)
Caused by: com.wx.hardware.huawei.api.service.HwException: one_IE
at com.wx.hardware.huawei.api.service.HwNetApiErrorDecoder.decode(HwNetApiErrorDecoder.java:34)
at feign.ResponseHandler.decodeError(ResponseHandler.java:136)
at feign.ResponseHandler.handleResponse(ResponseHandler.java:70)
at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:114)
at feign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:70)
at feign.ReflectiveFeign$FeignInvocationHandler.invoke(ReflectiveFeign.java:96)
at com.sun.proxy.$Proxy77.deviceInfo(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)