Search code examples
javaspringexceptionreturnwebclient

Java - Webclient - Return custom entity response when exception occurs


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


Solution

  • 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);
        }
    }