Enhancing mono with information for error handling

56 Views Asked by At

We are using Mono to handle calling REST services and I would like to enhance the exception handling by adding some extra information, to be used in case an exception has to be thrown.

Roughly, the code we have is of this form:

public ResultType callSomeService(Object param) {
   return addTimeoutAndRetryToMono(getMonoForServiceCall(param)).block();
}

The addTimeoutAndRetryToMono is a function that takes and returns a Mono and adds timeout, retry and error mapping. It is in the error map it defines that we throw, for instance, a TimeoutException.

I would like to enhance the exception being thrown by the callSomeService function with information regarding the service being called. For example, I would like to throw a custom exception with a message like "Timeout while calling {some path}".

Unfortunately, the "path" information is available only in the getMonoForServiceCall, which is generated based on an OpenAPI specification.

I have simplified the functions mentioned above to this:

Mono<T> getMonoForServiceCall(Object param) {
   ....
   // webClient comes from spring-webflux
   // prepareRequest handles the http method, path, query params, etc., fairly boiler-plate stuff
   ...
   WebClient.RequestBodySpec requestBuilder = prepareRequest(webClient, path, param);

   return requestBuilder.retrieve().bodyToMono(returnType);
}

and

Mono<T> addTimeoutAndRetryToMono(Mono<T> mono) {
  return mono.timeout(Duration.ofSeconds(10))
             .onErrorMap(t -> handleExceptions(t));
}

Throwable handleExceptions(Throwable t) {
  return new RestClientException("Here I would like to have the path of the API being called");
}

The simplest way would be to pass the "path" information around, catch and throw the custom exception in callSomeService, but there are quite a lot of these methods and it does feel "dirty".

I tried to use contextWrite in getMonoForService, adding the "path" to the context, but I can't seem to make it available in the error map.

The ideal sort of change would be done at the level of getMonoForService (where I have access to the path and other relevant fields) and addTimeoutAndRetryToMono (which is adding the error map), since these are in one of shared libraries and would result in a cleaner solution. The getMonoForServiceCall function should continue to return a Mono<T>.

0

There are 0 best solutions below