Search code examples
javaspringspring-boot

How to get HttpRequest in @ExceptionHandler with RestClientException?


I am developing an internal shared library in my company that needs to intercept all exceptions and format them into a single DTO (a bit simplified).

{
    "serviceName": "my-service-name",
    "errorCode": "ExternalRequestException",
    "externalServiceUrl": "http://external-service.com:8080/api/method-name?param=1"
    "externalErrorCode": "InvalidArgumentException",
    "externalErrorMessage": "Invalid argument param ...."
    "internalErrors": [],
}

I have no problem handling WebClientRequestException or WebClientResponseException in @ExceptionHandler because they contain a requestUrl or a whole HttpRequest to get the target url of the request. So, I can add org.springframework.web.reactive.function.client.Client.ClientResponse#createException to webClient as follows

var response = webClient
            .get()
            .uri(“http://external-service.com:8080/api/method-name?param=1”)
            .retrieve()
            .onStatus(HttpStatusCode::isError, ClientResponse::createException)
            .bodyToMono(String.class)
            .block();

and I will be 100% sure that the WebClientRequestException or WebClientResponseException thrown by this call will contain the request url (http://external-service.com:8080/api/method-name?param=1 in this example).

So, the main question is how to get the request information while restClient throws the exception? Maybe I need to develop some restClientInterceptor or something similar to enrich the standard exceptions with request specific information.

updates:

  • A little investigation from me: it seems that by default exceptions are created in org.springframework.web.client.StatusHandler#defaultHandler and HttpRequest is available in the context of this handler, but it is not used at all. This confuses me because I think the request information can be useful, especially for 4xx exceptions.
  • I have created a issue in a spring-framework project. https://github.com/spring-projects/spring-framework/issues/33814

Solution

  • And so, for many reasons, I decided to write my own implementation rest-client-call-exception. I posted it on github and published it on maven-central. Everybody welcome to use, discuss and contribute.