How to use #ControllerAdvice to handle webclient errors from the reactive stack (web flux -> spring) - spring-boot

I use webclient from weblux to send a request to a remote server. At this point, I can get error 400. I need to intercept it and send it to the client.
webClient
.post()
.uri(
)
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.body(
BodyInserters
.fromFormData()
.with()
.with()
)
.retrieve()
.onStatus(
HttpStatus::isError, response -> response.bodyToMono(String.class) // error body as String or other class
.flatMap(error -> Mono.error(new WrongCredentialsException(error)))
)
.bodyToMono(TResponse.class)
.doOnNext(...);
error
#ControllerAdvice
#Slf4j
public class ApplicationErrorHandler {
#ExceptionHandler(WrongCredentialsException.class)
public ResponseEntity<ErrorResponse> handleResponseException(WrongCredentialsException ex) {
// log.error("Error from WebClient - Status {}, Body {}", ex.getRawStatusCode(), ex.getResponseBodyAsString(), ex);
ErrorResponse error = new ErrorResponse();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(error);
}
#Data
#NoArgsConstructor
#AllArgsConstructor
public class ErrorResponse {
private String errorCode;
private String message;
}
rest api
#PostMapping
public ResponseEntity<String> send(#RequestBody Dto dto) {
log.debug("An notification has been send to user");
return new ResponseEntity<>(HttpStatus.OK);
}
I tried the options from here, but it didn't work out . Can someone explain how it works and how it can be configured for my case?

first case
return Objects.requireNonNull(oauthWebClient
.post()
.uri(uri)
.bodyValue(dto)
.attributes(oauth2AuthorizedClient(authorizedClient))
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.exchangeToMono(response -> {
HttpStatus httpStatus = response.statusCode();
if (httpStatus.is4xxClientError()) {
getErrFromClient(response, httpStatus);
}
if (httpStatus.is5xxServerError()) {
getErrFromServer(response, httpStatus);
}
return Mono.just(ResponseEntity.status(response.statusCode()));
})
.block())
.build();
}
private void getErrFromServer(DtoResponse response, HttpStatus httpStatus) {
String err = response.bodyToMono(String.class).toString();
log.error("HttpStatus: {}, message: {}", httpStatus, err);
HttpHeaders httpHeaders = response.headers().asHttpHeaders();
List<String> errorBody = httpHeaders.get("errBody");
assert errBody != null;
throw new CustomException(
"{ HttpStatus : " + httpStatus + " , message : " + errBody + " }");
}
private void getErrFromClient(DtoResponse response, HttpStatus httpStatus) {
String err = response.bodyToMono(String.class).toString();
log.error("HttpStatus: {}, err: {}", httpStatus, err);
HttpHeaders httpHeaders = response.headers().asHttpHeaders();
List<String> errorBody = httpHeaders.get("errBody");
assert errBody != null;
throw new CustomException(
"{ HttpStatus : " + httpStatus + " , message : " + errBody + " }");
}
and than
#ControllerAdvice
public class HandlerAdviceException {
#ExceptionHandler(CustomException.class)
public ResponseEntity<ErrorResponse> handleCustomException(CustomException e) {
//here your code
//for example:
String errMessage = e.getLocalizedMessage();
return ResponseEntity
.internalServerError()
.body(new ErrorResponse(ErrorCode.INTERNAL_ERROR, errMessage));
}
}
second case
return webClient
.post()
.uri(
properties......,
Map.of("your-key", properties.get...())
)
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.body(
prepare....()
)
.retrieve()
.bodyToMono(TokenResponse.class)
.doOnSuccess(currentToken::set);
}
Here, if successful, you will get the result you need, but if an error occurs, then you only need to configure the interceptor in the Advice Controller for WebClientResponseException.
#ControllerAdvice
#Slf4j
public class CommonRestExceptionHandler extends ResponseEntityExceptionHandler {
#ExceptionHandler(WebClientResponseException.class)
protected ResponseEntity<ApiErrorResponse> handleWebClientResponseException(WebClientResponseException ex) {
log.error(ex.getClass().getCanonicalName());
String errMessageAdditional = .....
final ApiErrorResponse apiError = ApiErrorResponse.builder()
.message(ex.getLocalizedMessage())
.status(HttpStatus.UNAUTHORIZED)
.build();
//if it needs
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add(.......);
return new ResponseEntity<>(apiError, httpHeaders, apiError.getStatus());
}
}

Related

Spring boot webflux annotated controller aspect trying to log the request Mono

So I have this around aspect applied to my controller method to log the request and response which works fine if I do not wrap the request in a Mono-
#PostMapping(
value = TRANSACTION_INSIGHTS_RETRIEVALS_PATH,
produces = MediaType.APPLICATION_JSON_VALUE,
consumes = MediaType.APPLICATION_JSON_VALUE
)
#AuditLogEvent(logEventType = LogEventTypeEnum.TRA_REQUEST_RESPONSE)
public Mono<ResponseEntity<TransactionInsights>> retrieveTransactionInsights(#Valid #RequestBody TransactionInsightsData transactionInsightsData) {
return Mono.just(transactionInsightsData)
.flatMap(request -> {
Optional<String> brand = retrieveBrand(request);
return transactionInsightsService.retrieveTransactionInsights(request, brand);
})
.map(ResponseEntity::ok);
}
My aspect -
#Slf4j
#Aspect
#Order(3)
#Component
#RequiredArgsConstructor
public class AuditLogEventAspect {
private final AuditEventManager auditEventManager;
#Around("#annotation(auditLogEvent) && args(request)")
public Object logAround(ProceedingJoinPoint joinPoint, AuditLogEvent auditLogEvent, Object request) throws Throwable {
Mono result = (Mono) joinPoint.proceed();
return Mono.deferContextual(ctx -> result
.doOnSuccess(o -> {
logSuccessExit(auditLogEvent, ctx.<Map<String, String>>get(CONTEXT_MAP), request, o)
.subscribe(auditEvent -> {
log.info("auditEvent {}", auditEvent);
});
})
.doOnError(o -> {
logErrorExit(auditLogEvent, ctx.<Map<String, String>>get(CONTEXT_MAP), request, (Exception) o)
.subscribe(auditEvent -> {
log.info("auditEvent {}", auditEvent);
});
})
.map(o -> result)
);
}
private Mono<AuditEvent> logErrorExit(AuditLogEvent auditLogEvent, Map<String, String> contextMap, Object request, Exception error) {
log.info("TRA request: {}", request);
log.info("TRA error response: {}", error.getMessage());
AuditEvent initialAuditEvent = auditEventManager.createAuditLogEvent(auditLogEvent, contextMap, request);
return auditEventManager.saveExceptionEvent(initialAuditEvent, error);
}
private Mono<AuditEvent> logSuccessExit(AuditLogEvent auditLogEvent, Map<String, String> contextMap, Object request, Object response) {
log.info("TRA request: {}", request);
log.info("TRA response: {}", response);
AuditEvent initialAuditEvent = auditEventManager.createAuditLogEvent(auditLogEvent, contextMap, request);
return auditEventManager.saveSuccessEvent(initialAuditEvent, response);
}
}
But ideally I'd like to wrap my request in a Mono like so -
#PostMapping(
value = TRANSACTION_INSIGHTS_RETRIEVALS_PATH,
produces = MediaType.APPLICATION_JSON_VALUE,
consumes = MediaType.APPLICATION_JSON_VALUE
)
#AuditLogEvent(logEventType = LogEventTypeEnum.TRA_REQUEST_RESPONSE)
public Mono<ResponseEntity<TransactionInsights>> retrieveTransactionInsights(#Valid #RequestBody Mono<TransactionInsightsData> transactionInsightsData) {
return transactionInsightsData
.flatMap(request -> {
Optional<String> brand = retrieveBrand(request);
return transactionInsightsService.retrieveTransactionInsights(request, brand);
})
.map(ResponseEntity::ok);
}
How can I change my aspect to work with arg Mono? I am new to reactive and webflux and learning so what am I missing?

Map Error using onErrorMap in WebFlux for Mono<Void>

I've two microservices, let us say a FrontEnd and BackEnd, for FrontEnd I'm using WebFlux and calling backend service using feign client as shown in below code excample, though the below code example works, but I wanted to have a generic exception handler using Function and feed onto onErrorMap
#RestController
#Slf4j
public class MyFrentEndService {
#Autowired
private MyBackEndService client;
#PostMapping(value="/hello", consumes="application/json")
public Mono<Void> sayHello(#Valid String msg) {
log.info("Message is {}", msg);
return Mono.create(sink-> {
try {
client.hello(msg);
}catch (FeignException e) {
System.out.println(e.status());
HttpStatus status = e.status() ==0 ? HttpStatus.SERVICE_UNAVAILABLE : HttpStatus.valueOf(e.status());
String message = e.getMessage();
sink.error(new ResponseStatusException(status, message));
}
sink.success();
});
}
}
Tried to use onErrorMap, but getting compilation error stating, use Mono instead of Mono<Void>
#RestController
#Slf4j
public class MyFrentEndService {
#Autowired
private MyBackEndService client;
#PostMapping(value="/hello", consumes="application/json")
public Mono<Void> sayHello(#Valid String msg) {
log.info("Message is {}", msg);
return Mono.fromSupplier(() -> {
client.hello(msg);
return null;
}).onErrorMap(e->{
HttpStatus status = e.status() ==0 } HttpStatus.SERVICE_UNAVAILABLE : HttpStatus.valueOf(e.status());
String message = e.getMessage();
return new ResponseStatusException(status, message);
});
}
}
How to use onErrorMap?
This error is unrelated to the operator onErrorMap. This code dont compile because the compiler can not infer the generic type returned by the method Mono.fromSupplier to be Void - you are returning null on the supplied function.
This should be corrected by doing the following:
#PostMapping(value="/hello", consumes="application/json")
public Mono<Void> sayHello(#Valid String msg) {
log.info("Message is {}", msg);
return Mono.<Void>fromSupplier(() -> {
client.hello(msg);
return null;
}).onErrorMap(e->{
HttpStatus status = e.status() ==0 ? HttpStatus.SERVICE_UNAVAILABLE : HttpStatus.valueOf(e.status());
String message = e.getMessage();
return new ResponseStatusException(status, message);
});
}
I think that it is more idiomatic to do the following:
#PostMapping(value="/hello", consumes="application/json")
public Mono<Void> sayHello(#Valid String msg) {
log.info("Message is {}", msg);
return Mono.fromRunnable(() -> {
client.hello(msg);
})
.then()
.onErrorMap(e->{
HttpStatus status = e.status() ==0 ? HttpStatus.SERVICE_UNAVAILABLE : HttpStatus.valueOf(e.status());
String message = e.getMessage();
return new ResponseStatusException(status, message);
});
}
Finally, I would advise against using blocking calls inside the reactive pipeline unless you really have to. (prefer WebClient or other nonblocking HTTP client over blocking clients as feign).

Unable to inject EJBTransactionRolledbackException

I am not able to inject EJBTransactionRolledbackException. I want to catch ConstraintViolationException. So first I need catch EJBTransactionRolledbackException then I can propagate to ConstraintViolationException exception using getCause().
How to inject it?
Below is my code.
#ControllerAdvice
public class RestExceptionProcessor extends ResponseEntityExceptionHandler {
// Here I am not able to inject EJBTransactionRolledbackException.
#ExceptionHandler({EJBTransactionRolledbackException.class})
protected ResponseEntity<Object> handleUniqueKeyViolation(EJBTransactionRolledbackException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
Throwable t = ex.getCause();
if(t != null &(t instanceof RollbackException)){
if(t != null &(t instanceof ConstraintViolationException)) {
return handleConstraintViolation((ConstraintViolationException) ex.getCause(), headers, status, request);
}
return handleConstraintViolation((RollbackException) ex.getCause(), headers, status, request);
}
String error = ex.getLocalizedMessage() + " " + ex.getMessage();
ApiError apiError = new ApiError(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), error);
return new ResponseEntity<Object>(apiError, new HttpHeaders(), apiError.getStatus());
}
#ExceptionHandler({RollbackException.class})
protected ResponseEntity<Object> handleConstraintViolation(RollbackException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
String error = ex.getLocalizedMessage() + " " + ex.getMessage();
ApiError apiError = new ApiError(HttpStatus.CONFLICT, ex.getLocalizedMessage(), error);
return new ResponseEntity<Object>(apiError, new HttpHeaders(), apiError.getStatus());
}
#ExceptionHandler({ConstraintViolationException.class})
protected ResponseEntity<Object> handleConstraintViolation(ConstraintViolationException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
List<String> errors = new ArrayList<String>();
for (ConstraintViolation<?> violation : ex.getConstraintViolations()) {
errors.add(violation.getRootBeanClass().getName() + " " +
violation.getPropertyPath() + ": " + violation.getMessage());
}
ApiError apiError = new ApiError(HttpStatus.CONFLICT, ex.getLocalizedMessage(), error);
return new ResponseEntity<Object>(apiError, new HttpHeaders(), apiError.getStatus());
}
}
And my ApiErrors class is like below:
public class ApiError {
private HttpStatus status;
private String message;
private List<String> errors;
public ApiError(HttpStatus status, String message, List<String> errors) {
super();
this.status = status;
this.message = message;
this.errors = errors;
}
public ApiError(HttpStatus status, String message, String error) {
super();
this.status = status;
this.message = message;
this.errors = Arrays.asList(error);
}
}

Spring Resttemplate exception handling

Below is the code snippet; basically, I am trying to propagate the exception when the error code is anything other than 200.
ResponseEntity<Object> response = restTemplate.exchange(url.toString().replace("{version}", version),
HttpMethod.POST, entity, Object.class);
if(response.getStatusCode().value()!= 200){
logger.debug("Encountered Error while Calling API");
throw new ApplicationException();
}
However in the case of a 500 response from the server I am getting the exception
org.springframework.web.client.HttpServerErrorException: 500 Internal Server Error
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:94) ~[spring-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
Do I really need to wrap the rest template exchange method in try? What would then be the purpose of codes?
You want to create a class that implements ResponseErrorHandler and then use an instance of it to set the error handling of your rest template:
public class MyErrorHandler implements ResponseErrorHandler {
#Override
public void handleError(ClientHttpResponse response) throws IOException {
// your error handling here
}
#Override
public boolean hasError(ClientHttpResponse response) throws IOException {
...
}
}
[...]
public static void main(String args[]) {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setErrorHandler(new MyErrorHandler());
}
Also, Spring has the class DefaultResponseErrorHandler, which you can extend instead of implementing the interface, in case you only want to override the handleError method.
public class MyErrorHandler extends DefaultResponseErrorHandler {
#Override
public void handleError(ClientHttpResponse response) throws IOException {
// your error handling here
}
}
Take a look at its source code to have an idea of how Spring handles HTTP errors.
Spring cleverly treats http error codes as exceptions, and assumes that your exception handling code has the context to handle the error. To get exchange to function as you would expect it, do this:
try {
return restTemplate.exchange(url, httpMethod, httpEntity, String.class);
} catch(HttpStatusCodeException e) {
return ResponseEntity.status(e.getRawStatusCode()).headers(e.getResponseHeaders())
.body(e.getResponseBodyAsString());
}
This will return all the expected results from the response.
You should catch a HttpStatusCodeException exception:
try {
restTemplate.exchange(...);
} catch (HttpStatusCodeException exception) {
int statusCode = exception.getStatusCode().value();
...
}
Another solution is the one described here at the end of this post by "enlian":
http://springinpractice.com/2013/10/07/handling-json-error-object-responses-with-springs-resttemplate
try{
restTemplate.exchange(...)
} catch(HttpStatusCodeException e){
String errorpayload = e.getResponseBodyAsString();
//do whatever you want
} catch(RestClientException e){
//no response payload, tell the user sth else
}
Spring abstracts you from the very very very large list of http status code. That is the idea of the exceptions. Take a look into org.springframework.web.client.RestClientException hierarchy:
You have a bunch of classes to map the most common situations when dealing with http responses. The http codes list is really large, you won't want write code to handle each situation. But for example, take a look into the HttpClientErrorException sub-hierarchy. You have a single exception to map any 4xx kind of error. If you need to go deep, then you can. But with just catching HttpClientErrorException, you can handle any situation where bad data was provided to the service.
The DefaultResponseErrorHandler is really simple and solid. If the response status code is not from the family of 2xx, it just returns true for the hasError method.
I have handled this as below:
try {
response = restTemplate.postForEntity(requestUrl, new HttpEntity<>(requestBody, headers), String.class);
} catch (HttpStatusCodeException ex) {
response = new ResponseEntity<String>(ex.getResponseBodyAsString(), ex.getResponseHeaders(), ex.getStatusCode());
}
A very simple solution can be:
try {
requestEntity = RequestEntity
.get(new URI("user String"));
return restTemplate.exchange(requestEntity, String.class);
} catch (RestClientResponseException e) {
return ResponseEntity.status(e.getRawStatusCode()).body(e.getResponseBodyAsString());
}
If you use pooling (http client factory) or load balancing (eureka) mechanism with your RestTemplate, you will not have the luxury of creating a new RestTemplate per class. If you are calling more than one service you cannot use setErrorHandler because if would be globally used for all your requests.
In this case, catching the HttpStatusCodeException seems to be the better option.
The only other option you have is to define multiple RestTemplate instances using the #Qualifier annotation.
Also - but this is my own taste - I like my error handling snuggled tightly to my calls.
The code of exchange is below:
public <T> ResponseEntity<T> exchange(String url, HttpMethod method,
HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables) throws RestClientException
Exception RestClientException has HttpClientErrorException and HttpStatusCodeException exception.
So in RestTemplete there may occure HttpClientErrorException and HttpStatusCodeException exception.
In exception object you can get exact error message using this way: exception.getResponseBodyAsString()
Here is the example code:
public Object callToRestService(HttpMethod httpMethod, String url, Object requestObject, Class<?> responseObject) {
printLog( "Url : " + url);
printLog( "callToRestService Request : " + new GsonBuilder().setPrettyPrinting().create().toJson(requestObject));
try {
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Object> entity = new HttpEntity<>(requestObject, requestHeaders);
long start = System.currentTimeMillis();
ResponseEntity<?> responseEntity = restTemplate.exchange(url, httpMethod, entity, responseObject);
printLog( "callToRestService Status : " + responseEntity.getStatusCodeValue());
printLog( "callToRestService Body : " + new GsonBuilder().setPrettyPrinting().create().toJson(responseEntity.getBody()));
long elapsedTime = System.currentTimeMillis() - start;
printLog( "callToRestService Execution time: " + elapsedTime + " Milliseconds)");
if (responseEntity.getStatusCodeValue() == 200 && responseEntity.getBody() != null) {
return responseEntity.getBody();
}
} catch (HttpClientErrorException exception) {
printLog( "callToRestService Error :" + exception.getResponseBodyAsString());
//Handle exception here
}catch (HttpStatusCodeException exception) {
printLog( "callToRestService Error :" + exception.getResponseBodyAsString());
//Handle exception here
}
return null;
}
Here is the code description:
In this method you have to pass request and response class. This method will automatically parse response as requested object.
First of All you have to add message converter.
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
Then you have to add requestHeader.
Here is the code:
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Object> entity = new HttpEntity<>(requestObject, requestHeaders);
Finally, you have to call exchange method:
ResponseEntity<?> responseEntity = restTemplate.exchange(url, httpMethod, entity, responseObject);
For prety printing i used Gson library.
here is the gradle : compile 'com.google.code.gson:gson:2.4'
You can just call the bellow code to get response:
ResponseObject response=new RestExample().callToRestService(HttpMethod.POST,"URL_HERE",new RequestObject(),ResponseObject.class);
Here is the full working code:
import com.google.gson.GsonBuilder;
import org.springframework.http.*;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;
public class RestExample {
public RestExample() {
}
public Object callToRestService(HttpMethod httpMethod, String url, Object requestObject, Class<?> responseObject) {
printLog( "Url : " + url);
printLog( "callToRestService Request : " + new GsonBuilder().setPrettyPrinting().create().toJson(requestObject));
try {
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Object> entity = new HttpEntity<>(requestObject, requestHeaders);
long start = System.currentTimeMillis();
ResponseEntity<?> responseEntity = restTemplate.exchange(url, httpMethod, entity, responseObject);
printLog( "callToRestService Status : " + responseEntity.getStatusCodeValue());
printLog( "callToRestService Body : " + new GsonBuilder().setPrettyPrinting().create().toJson(responseEntity.getBody()));
long elapsedTime = System.currentTimeMillis() - start;
printLog( "callToRestService Execution time: " + elapsedTime + " Milliseconds)");
if (responseEntity.getStatusCodeValue() == 200 && responseEntity.getBody() != null) {
return responseEntity.getBody();
}
} catch (HttpClientErrorException exception) {
printLog( "callToRestService Error :" + exception.getResponseBodyAsString());
//Handle exception here
}catch (HttpStatusCodeException exception) {
printLog( "callToRestService Error :" + exception.getResponseBodyAsString());
//Handle exception here
}
return null;
}
private void printLog(String message){
System.out.println(message);
}
}
Thanks :)
To extedend #carcaret answer a bit....
Consider your response errors are returned by json message. For example the API may return 204 as status code error and a json message as error list. In this case you need to define which messages should spring consider as error and how to consume them.
As a sample your API may return some thing like this, if error happens:
{ "errorCode":"TSC100" , "errorMessage":"The foo bar error happend" , "requestTime" : "202112827733" .... }
To consume above json and throw a custom exception, you can do as below:
First define a class for mapping error ro object
//just to map the json to object
public class ServiceErrorResponse implements Serializable {
//setter and getters
private Object errorMessage;
private String errorCode;
private String requestTime;
}
Now define the error handler:
public class ServiceResponseErrorHandler implements ResponseErrorHandler {
private List<HttpMessageConverter<?>> messageConverters;
#Override
public boolean hasError(ClientHttpResponse response) throws IOException {
return (response.getStatusCode().is4xxClientError() ||
response.getStatusCode().is5xxServerError());
}
#Override
public void handleError(ClientHttpResponse response) throws IOException {
#SuppressWarnings({ "unchecked", "rawtypes" })
HttpMessageConverterExtractor<ServiceErrorResponse> errorMessageExtractor =
new HttpMessageConverterExtractor(ServiceErrorResponse.class, messageConverters);
ServiceErrorResponse errorObject = errorMessageExtractor.extractData(response);
throw new ResponseEntityErrorException(
ResponseEntity.status(response.getRawStatusCode())
.headers(response.getHeaders())
.body(errorObject)
);
}
public void setMessageConverters(List<HttpMessageConverter<?>> messageConverters) {
this.messageConverters = messageConverters;
}
}
The custom Exception will be:
public class ResponseEntityErrorException extends RuntimeException {
private ResponseEntity<ServiceErrorResponse> serviceErrorResponseResponse;
public ResponseEntityErrorException(ResponseEntity<ServiceErrorResponse> serviceErrorResponseResponse) {
this.serviceErrorResponseResponse = serviceErrorResponseResponse;
}
public ResponseEntity<ServiceErrorResponse> getServiceErrorResponseResponse() {
return serviceErrorResponseResponse;
}
}
To use it:
RestTemplateResponseErrorHandler errorHandler = new
RestTemplateResponseErrorHandler();
//pass the messageConverters to errror handler and let it convert json to object
errorHandler.setMessageConverters(restTemplate.getMessageConverters());
restTemplate.setErrorHandler(errorHandler);
This is how to handle exceptions in Rest Template
try {
return restTemplate.exchange("URL", HttpMethod.POST, entity, String.class);
}
catch (HttpStatusCodeException e)
{
return ResponseEntity.status(e.getRawStatusCode()).headers(e.getResponseHeaders())
.body(e.getResponseBodyAsString());
}
Here is my POST method with HTTPS which returns a response body for any type of bad responses.
public String postHTTPSRequest(String url,String requestJson)
{
//SSL Context
CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
//Initiate REST Template
RestTemplate restTemplate = new RestTemplate(requestFactory);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
//Send the Request and get the response.
HttpEntity<String> entity = new HttpEntity<String>(requestJson,headers);
ResponseEntity<String> response;
String stringResponse = "";
try {
response = restTemplate.postForEntity(url, entity, String.class);
stringResponse = response.getBody();
}
catch (HttpClientErrorException e)
{
stringResponse = e.getResponseBodyAsString();
}
return stringResponse;
}
I fixed it by overriding the hasError method from DefaultResponseErrorHandler class:
public class BadRequestSafeRestTemplateErrorHandler extends DefaultResponseErrorHandler
{
#Override
protected boolean hasError(HttpStatus statusCode)
{
if(statusCode == HttpStatus.BAD_REQUEST)
{
return false;
}
return statusCode.isError();
}
}
And you need to set this handler for restemplate bean:
#Bean
protected RestTemplate restTemplate(RestTemplateBuilder builder)
{
return builder.errorHandler(new BadRequestSafeRestTemplateErrorHandler()).build();
}
Read about global exception handling in global exception handler add the below method. this will work.
#ExceptionHandler( {HttpClientErrorException.class, HttpStatusCodeException.class, HttpServerErrorException.class})
#ResponseBody
public ResponseEntity<Object> httpClientErrorException(HttpStatusCodeException e) throws IOException {
BodyBuilder bodyBuilder = ResponseEntity.status(e.getRawStatusCode()).header("X-Backend-Status", String.valueOf(e.getRawStatusCode()));
if (e.getResponseHeaders().getContentType() != null) {
bodyBuilder.contentType(e.getResponseHeaders().getContentType());
}
return bodyBuilder.body(e.getResponseBodyAsString());
}
There is also an option to use TestRestTemplate. It is very useful for integration and E2E tests, when you need to validate all status codes manually (for example in negative test-cases).
TestRestTemplate is fault-tolerant. This means that 4xx and 5xx do not result in an exception being thrown and can instead be detected via the response entity and its status code.
Try using #ControllerAdvice. This allows you to handle the exception only once and have all 'custom' handled exceptions in one place.
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/ControllerAdvice.html
example
#ControllerAdvice
public class MyExceptionHandler extends ResponseEntityExceptionHandler{
#ExceptionHandler(MyException.class)
protected ResponseEntity<Object> handleMyException(){
MyException exception,
WebRequest webRequest) {
return handleExceptionInternal(
exception,
exception.getMessage(),
exception.getResponseHeaders(),
exception.getStatusCode(),
webRequest);
}

Spring Boot: How to handle 400 error caused by #RequestParam?

public String(#RequestParam Integer id) {
// ...
}
If id parameter cannot be found in the current request, I will get 400 status code with empty response body. Now I want to return JSON string for this error, how can I make it?
PS: I don't want to use #RequestParam(required = false)
try to use #PathVariable, hope it will meets your requirement.
#RequestMapping(value = "/user/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<User> getUser(#PathVariable("id") long id) {
System.out.println("Fetching User with id " + id);
User user = userService.findById(id);
if (user == null) {
System.out.println("User with id " + id + " not found");
return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<User>(user, HttpStatus.OK);
}
I've made it.
Just override handleMissingServletRequestParameter() method in your own ResponseEntityExceptionHandler class.
#Override
protected ResponseEntity<Object> handleMissingServletRequestParameter(MissingServletRequestParameterException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
log.warn("miss Request Param");
return new ResponseEntity<>(new FoxResponse(ErrorCode.ARG_INVALID), status);
}
Just had the same problem, but exception thrown is MethodArgumentTypeMismatchException. With #ControllerAdvice error handler all data about #RequestParam error can be retrieved. Here is complete class that worked for me
#ControllerAdvice
#RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public class ControllerExceptionHandler {
#ExceptionHandler(value = {MethodArgumentTypeMismatchException.class})
#ResponseStatus(value = HttpStatus.BAD_REQUEST)
#ResponseBody
public Map<String, String> handleServiceCallException(MethodArgumentTypeMismatchException e) {
Map<String, String> errMessages = new HashMap<>();
errMessages.put("error", "MethodArgumentTypeMismatchException");
errMessages.put("message", e.getMessage());
errMessages.put("parameter", e.getName());
errMessages.put("errorCode", e.getErrorCode());
return errMessages;
}
}

Resources