I am fairly new to Java/Spring domain and I am trying to utilize @ControllerAdvice in my Spring Boot application. The ControllerAdvice catches the exception but doesn't show my custom response.
following is the snap shot of RestController which is throwing the exception
ResponseEntity<MyClass> response = new ResponseEntity<MyClass>(HttpStatus.OK);
try {
response = restTemplate.exchange(url, HttpMethod.GET, entity, MyClass.class);
} catch (HttpClientErrorException ex) {
throw ex;
}catch (HttpServerErrorException ex) {
logger.debug(ex.getMessage() + " Server Status Code - " + ex.getStatusCode());
}
catch(Exception ex) {
logger.debug(ex.getMessage() + " Generic Exception ");
}
following is the @ControllerAdvice
@ControllerAdvice
public class GlobalExceptionHandler extends Exception {
@ExceptionHandler(HttpClientErrorException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse errorHandle(HttpClientErrorException ex) {
String responseBody = ex.getResponseBodyAsString();
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
ErrorResponse errorResponse = new ErrorResponse();
try {
errorResponse = mapper.readValue(responseBody, ErrorResponse.class);
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return errorResponse;
}
}
and other classes
@JsonIgnoreProperties
public class ErrorResponse {
@JsonProperty("error")
public Error error;
@JsonProperty("version")
public String version;
}
public class Error {
@JsonProperty("code")
public String Code;
@JsonProperty("message")
public String Message;
public String getCode() {
return Code;
}
public void setCode(String code) {
Code = code;
}
public String getMessage() {
return Message;
}
public void setMessage(String message) {
Message = message;
}
}
the error I am getting when using POSTMAN is
{
"timestamp": "2019-11-20T05:42:24.126+0000",
"status": 404,
"error": "Not Found",
"message": "400 Bad Request",
"path": "myApi/somecontroller"
}
and the error I get on browser is as follows
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Tue Nov 19 23:40:26 CST 2019
There was an unexpected error (type=Not Found, status=404).
400 Bad Request
any idea/suggestion why this behavior? I was expecting an JSON representation of ErrorResponse class.
Update