0

We are trying to put Spring Cloud Netflix into production environment. For now we encounter a problem about business logic error handling.

We're using Feign as HTTP REST client. Microservice A needs to invoke microservice B which is deployed in different JVM(or physical server). Microservice B may return some error message which belongs to business. For instance A needs to query order information from B but the order ID may not exist so B has to return the error message that tells A this order doesn't exist. A has to do if-else judgement from the return message to determine if there are erorrs, then code will be like the following snippet:

//remoteServiceA is an interface annotated with @FeignClient
resultA = remoteServiceA.foo();
if (resultA.hasError) {

} else {

}

resultB = remoteServiceB.foo();
if (resultB.hasError) {

} else {

}

// ... ...

There are so many if-else so that it's not graceful enough. What we want is remoteServieA.foo() can throw a self-defined runtime exception such as OrderNotExistException. Any idea to achieve this goal?

4

2 回答 2

1

我已经解决了这个问题。我自定义了ErrorDecoderFeign 的组件,可以根据 HTTP 原始响应抛出自己的异常。

于 2017-04-21T06:42:55.960 回答
0

如果你启用了 Hystrix,你应该能够将你的 serviceA.foo() 包装在一个 try 块中,并在你的远程服务中抛出一个异常。

try {
    serviceA.foo();
} catch(HystrixRuntimeException ex) {
    throw new OrderNotExistException("Error message");
}

您仍然必须考虑到,如果您的远程服务没有响应,或者发生其他错误,您可以捕获这种异常。也许您可以找到有关发生的异常的信息并决定是否应该抛出异常。

我想到的第一件事,但在我的一个项目中工作。

于 2016-08-11T17:08:27.913 回答