Handle success/error response using Webclient

78 views Asked by At

i have an api which i am calling using WebClient in Spring Boot.When the the api call is successfull (i.e. 200 status ) i get the response as

{
  "id": 123,
  "username": "john_doe",
  "email": "[email protected]",
  "createdAt": "2023 march"
}

and when the api call is unsuccessful (400 or 500 status range) then response is

{
    "error": "details",
    "code": "400",
    "message": "Bad Request",
    "details": "The request body is missing a required field."
}

How to handle it.I have written the below code .Its working for sucess call but i am not able to failure status code.

  • UserResponse - Pojo mapping success response

  • ApiErrorResponse - Pojo mapping error response

    public class ResponseWrapper { private final boolean success; private final String message; private UserResponse userResponse; private ApiErrorResponse apiErrorResponse;

Code

public ResponseWrapper fetchUserData2(UserRequest userRequest) {
        UserResponse userResponse = apiWebClient.post()
                .uri("https://demo4108264.mockable.io/test")
                .body(Mono.just(userRequest), UserRequest.class)
                .retrieve()
                
                .onStatus(HttpStatus::is4xxClientError, response ->
                response.bodyToMono(ApiErrorResponse.class)
                        .flatMap(errorResponse -> Mono.error(new CustomApiException(errorResponse)))
        )
                .bodyToMono(UserResponse.class)
                .block();
        
        // Process the response based on success or error
        if (userResponse != null) {
            System.out.println(" success " + userResponse.getId());
            // Handle success
            return new ResponseWrapper(true, "API call successful", userResponse,null);
        } else {
            System.out.println(" error occured " );
            return new ResponseWrapper(false, "API call failed", null,null);
        }
0

There are 0 answers