Reputation: 1163
I want to throw my custom exceptions with the following conditions:
If I am getting proper error response in json format, I want to deserialize it and throw my exception named CommonException inside onStatus()
If I am receiving an HTML content as part of response or deserialization didnt happen successfully then I want to throw GenericException which I am creating inside onErrorMap()
While throwing a GenericException, I want to pass the same HttpStatus code to upstream which I am getting from downstream response.
IdVerificationResponse idVerificationResponse = client.get()
.uri(idVerificationUrl)
.headers(headers -> headers.addAll(httpEntity.getHeaders()))
.retrieve()
.onStatus(HttpStatus::isError, response ->
//Throw this one only if deserialization of error response to IdVerificationErrorResponse class happens successfully
response.bodyToMono(IdVerificationErrorResponse.class)
.flatMap(error -> Mono.error(CommonException.builder().message(error.getCustomMessage()).build()))
)
.bodyToMono(IdVerificationResponse.class)
.onErrorMap(error -> {
//Come over here only if there is an error in deserialization in onStatus()
//How to get the HttpStatus we are getting as part of error response from the downstream
HttpStatus httpStatus = HttpStatus.BAD_REQUEST;
ApiErrorDetails errorDetailsObj = ApiErrorDetails.builder().errorCode(httpStatus.name()).errorDescription("Error related to HTML")
.errorDetails("Error related to HTML").build();
ErrorDetails errorDetails = ErrorDetails.builder().errors(errorDetailsObj).build();
return GenericException.builder().errorDetails(errorDetails).httpStatus(httpStatus).build();
}).block();
Currently onErrorMap() is getting called everytime and overriding the exception I am throwing inside onStatus()
Upvotes: 0
Views: 5212
Reputation: 1163
Found the solution
IdVerificationResponse idVerificationResponse = client.get()
.uri(processCheckUrl)
.headers(headers -> headers.addAll(httpEntity.getHeaders()))
.retrieve()
.onStatus(HttpStatus::isError, response -> {
HttpStatus errorCode = response.statusCode();
return response.bodyToMono(IdVerificationErrorResponse.class)
.onErrorMap(error -> new Exception("Throw your generic exception over here if there is any error in deserialization"))
.flatMap(error -> Mono.error(new Exception("Throw your custom exception over here after successful deserialization")));
})
.bodyToMono(IdVerificationResponse.class).block();
Upvotes: 2