經(jīng)過嘗試和查閱資料,Springcloud處理下游服務(wù)的異常是是通過默認(rèn)的ErrorDecoder實現(xiàn)處理的,最終上游業(yè)務(wù)獲取拋出的異常處理都是FeignException處理,到時上游業(yè)務(wù)統(tǒng)一異常處理造成困擾别威,下面解決方式為:
@Slf4j
@Configuration
public class ExceptionErrorDecoder implements ErrorDecoder {
@Override
public Exception decode(String methodKey, Response response) {
try {
if (response.body() != null) {
ExceptionInfo exceptionInfo = JSON.parseObject(Util.toString(response.body().asReader()), new TypeReference<ExceptionInfo>() {
});
Class clazz = Class.forName(exceptionInfo.getException());
return (Exception) clazz.getDeclaredConstructor(String.class).newInstance(exceptionInfo.getMessage());
}
} catch (Exception e) {
e.printStackTrace();
}
return FeignException.errorStatus(methodKey, response);
}
}
主要分析了返回的body的內(nèi)容,主要結(jié)構(gòu)如下:
{
"timestamp": 1538202442624,
"status": 500,
"error": "Internal Server Error",
"exception": "com.crazy.cloud.common.exception.DataConflictException",
"message": "手機(jī)已注冊",
"path": "/users"
}
@Data
public class ExceptionInfo{
private Long timestamp;
private Integer status;
//異常包結(jié)構(gòu)-"com.crazy.cloud.common.exception.DataConflictException"
private String exception;
//信息--手機(jī)已注冊
private String message;
private String path;
private String error;
}
分析能夠得到--我們有了完整的包結(jié)構(gòu)和message,所以我們完全可以通過反射生成一個同樣的異常對象吁讨,這樣我們在上游業(yè)務(wù)就可以被controllerAdvice捕獲到,從而達(dá)到統(tǒng)一異常處理的目的峦朗。