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?

Neo
  • 2,196
  • 5
  • 32
  • 58
  • In the true spirit of REST APIs, the http error code returned should be self explanatory. So if you are querying for an order (a resource) and gets a 404, it means "resource not found" which is "order not found". – Tito Apr 19 '17 at 16:45

2 Answers2

1

I've solved this problem. I customized the ErrorDecoder component of Feign, in which I can throw my own exception according to the HTTP original response.

Neo
  • 2,196
  • 5
  • 32
  • 58
0

If you have Hystrix enabled, you should be able to wrap you serviceA.foo() in a try block and throw an exception in your remote service.

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

You still have to take in account that you can catch that kind of exception if your remote service doesn't answer, or if an other error happens. Maybe you can find information the exception about what happened and decide if you should throw your exception.

First thing that comes to my mind but work in one of my project.