1

I want to return a custom entity response when a specific exception occurs (Example, Unauthorized exception). I know how to catch it but only to return a custom exception;

public Mono<ResponseEntity<MagentoAdobeOrderResponse>> getOrder(String orderId, String token){
         return webClient.get()
                       .uri(orderUrl+"/"+orderId)
                       .header(HttpHeaders.CACHE_CONTROL, "no-cache")
                       .header(HttpHeaders.ACCEPT, "*/*")
                       .header(HttpHeaders.ACCEPT_ENCODING, "deflate, br")
                       .header(HttpHeaders.CONNECTION, "keep-alive")
                       .header(HttpHeaders.AUTHORIZATION, "Bearer "+token)
                       .retrieve()
               .toEntity(MagentoAdobeOrderResponse.class);
               .onErrorMap(Unauthorized.class, ex -> new AdobeMagentoUnauthorizedException(String.valueOf(HttpStatus.UNAUTHORIZED.value()),
                                    ButttonMilesConstants.BANK_PROBLEMS_ERROR_MESSAGE));
   }

What I want is something like this:

public Mono<ResponseEntity<MagentoAdobeOrderResponse>> getOrder(String orderId, String token){
             return webClient.get()
                           .uri(orderUrl+"/"+orderId)
                           .header(HttpHeaders.CACHE_CONTROL, "no-cache")
                           .header(HttpHeaders.ACCEPT, "*/*")
                           .header(HttpHeaders.ACCEPT_ENCODING, "deflate, br")
                           .header(HttpHeaders.CONNECTION, "keep-alive")
                           .header(HttpHeaders.AUTHORIZATION, "Bearer "+token)
                           .retrieve()
                   .toEntity(MagentoAdobeOrderResponse.class);
                   .onErrorMap(Unauthorized.class, return new ResponseEntity<MagentoAdobeOrderResponse>());
   }

it's possible?

Regards

waridc
  • 21
  • 1
  • 9
  • Does this answer your question? [Getting the response body in error case with Spring WebClient](https://stackoverflow.com/questions/71643036/getting-the-response-body-in-error-case-with-spring-webclient) – Alex Jan 18 '23 at 00:05

1 Answers1

1

You can catch your exception in a class annotated with @ControllerAdvice and then return your custom entity response. A @ControllerAdvice class can help you handle exceptions thrown by your application.

Something that might look like what you want to do:

@ControllerAdvice
public class ControllerAdviceResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(value = {AdobeMagentoUnauthorizedException.class})
    protected ResponseEntity<Object> handleAdobeMagentoUnauthorizedException(
            RuntimeException exception, 
            ServletWebRequest request
    ) {
        MagentoAdobeOrderResponse response = new MagentoAdobeOrderResponse();
        return new ResponseEntity<>(response, HttpStatus.UNAUTHORIZED);
    }
}
Marc Bannout
  • 388
  • 4
  • 15