Spring ControllerAdvice does not return response body? - java

I have the following ControllerAdvice, that handles JsonParseException (I use Spring and Jackson)
#ControllerAdvice
public class ControllerExceptionHandler extends ResponseEntityExceptionHandler {
#ExceptionHandler(JsonParseException.class)
public ResponseEntity<Object> handleInvalidJson(JsonParseException ex, WebRequest request){
Map<String,Object> body = new LinkedHashMap<>();
body.put("timestamp", LocalDateTime.now());
body.put("message","Invalid Json");
return new ResponseEntity(body, HttpStatus.BAD_REQUEST);
}
}
Fore some reason, It doesn't work when I send a bad json request to the server, only returns 400. When I change the HttpStatus, it still returns 400 so it seems like the advice doesn't really run.

ResponseEntityExceptionHandler already implements a lot of different ExceptionHandlers. HttpMessageNotReadableException is one of them:
else if (ex instanceof HttpMessageNotReadableException) {
HttpStatus status = HttpStatus.BAD_REQUEST;
return handleHttpMessageNotReadable((HttpMessageNotReadableException) ex, headers, status, request);
}
Simply remove the inheritance:
#ControllerAdvice
public class TestExceptionHandler {
#ExceptionHandler(JsonParseException.class)
public ResponseEntity<Map<String,Object>> handleInvalidJson(JsonParseException ex, WebRequest request){
Map<String,Object> body = new LinkedHashMap<>();
body.put("timestamp", LocalDateTime.now());
body.put("message","Invalid Json");
return new ResponseEntity<>(body, HttpStatus.I_AM_A_TEAPOT);
}
}

Related

How to get rid of spring boot's default exception?

I am new to spring boot and I am adding custom exceptions to my controller through controllerAdvisor.
In MyController.class, I am doing three operations
Get all the tickets present in the database.
Get ticket by id
Create the ticket.
Below mentioned class is MyController.class.
#RestController
public class MyController {
#Autowired
private TicketServiceImpl ticketService;
#GetMapping(/ticket)
public ResponseEntity<?> getAllTickets() {
List<Ticket> list=(List<Ticket>)ticketService.findAll();
return new ResponseEntity<>(list, HttpStatus.OK);
}
#GetMapping(Constant.BASE_URL+"/{id}")
public ResponseEntity<Ticket> getTicketById(#PathVariable("id") long id) {
Optional<Ticket> ticketData = Optional.ofNullable(ticketService.get(id));
if(!ticketData.isPresent()){
throw new RecordNotFoundException("id-" + id);
}
return new ResponseEntity<>(ticketData.get(), HttpStatus.OK);
}
#PostMapping(/ticket)
public ResponseEntity<Ticket> createTicket(#RequestBody Ticket ticket) {
ticketService.save(ticket);
return new ResponseEntity<>(ticket, HttpStatus.CREATED);
}
}
Below class is my custom exception handle class where I am handling my custom exceptions.
#SuppressWarnings({"unchecked","rawtypes"})
#ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {
#ExceptionHandler(Exception.class)
public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) {
List<String> details = new ArrayList<>();
details.add(ex.getLocalizedMessage());
ErrorResponse error = new ErrorResponse("Server Error", details);
return new ResponseEntity(error, HttpStatus.INTERNAL_SERVER_ERROR);
}
#ExceptionHandler(RecordNotFoundException.class)
public final ResponseEntity<Object> handleUserNotFoundException(RecordNotFoundException ex, WebRequest request) {
List<String> details = new ArrayList<>();
details.add(ex.getLocalizedMessage());
ErrorResponse error = new ErrorResponse("Record Not Found", details);
return new ResponseEntity(error, HttpStatus.NOT_FOUND);
}
#Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
List<String> details = new ArrayList<>();
for(ObjectError error : ex.getBindingResult().getAllErrors()) {
details.add(error.getDefaultMessage());
}
ErrorResponse error = new ErrorResponse("Validation Failed", details);
return new ResponseEntity(error, HttpStatus.BAD_REQUEST);
}
}
The below class is specific for not found exceptions.
#ResponseStatus(HttpStatus.NOT_FOUND)
public class RecordNotFoundException extends RuntimeException {
public RecordNotFoundException(String exception) {
super(exception);
}
}
In application.properties, I am adding these three conditions
server.error.whitelabel.enabled=false
spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false
When I hit my server with GET API http://localhost:8080/ticke .It should throw bad request exception but its throwing Not found "404" exception and when I hit GET API http://localhost:8080/ticket/24, in this my id is not created. Hence, it should return resource not found exception.But, its returning, 500 internal server error.
Please advise on this.
The error you are getting is because Spring was not able to find the endpoint you are looking for. So it does not apply any controller advices to it, since it did not find a controller that maps to the requested URL.
Here is a small article explaining it in a little more detail.

How to return the ConstraintViolationException messages in the response body?

I am developing a Spring Boot based REST API. I am validating the input entities using custom ConstraintValidator annotations. My problem is that I cannot return the ConstraintViolationException messages in the response. My exception handler does not catch the exceptions (maybe because they're wrapped in another types of exceptions).
Can I please get some advice on how to handle the situation?
I've searched all over the Internet but I couldn't find a fitting solution for me and I've also wasted some hours doing so.
Example annotation:
#Documented
#Retention(RUNTIME)
#Target({FIELD, PARAMETER})
#Constraint(validatedBy = BirthDateValidator.class)
public #interface ValidBirthDate {
String message() default "The birth date is not valid.";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Validator class:
public class BirthDateValidator extends FieldValidationBase implements ConstraintValidator<ValidBirthDate, LocalDate> {
private static final Logger LOGGER = LoggerFactory.getLogger(BirthDateValidator.class);
#Override
public void initialize(ValidBirthDate constraintAnnotation) {
}
#Override
public boolean isValid(LocalDate birthDate, ConstraintValidatorContext constraintValidatorContext) {
constraintValidatorContext.disableDefaultConstraintViolation();
LOGGER.info("Starting the validation process for birth date {}.", birthDate);
if(birthDate == null) {
constraintValidatorContext.buildConstraintViolationWithTemplate("The birth date is null.")
.addConstraintViolation();
return false;
}
//other validations
return true;
}
Model class:
public class Manager extends BaseUser {
//other fields
#Valid
#ValidBirthDate
private LocalDate birthDate;
//setters & getters
Exception handler:
#ExceptionHandler(value = ConstraintViolationException.class)
public ResponseEntity handleConstraintViolationException(ConstraintViolationException ex, WebRequest request) {
List<String> errors = new ArrayList<>();
for (ConstraintViolation<?> violation : ex.getConstraintViolations()) {
errors.add(violation.getRootBeanClass().getName() + ": " + violation.getMessage());
}
Error response = new Error(errors);
return new ResponseEntity<Object>(response, new HttpHeaders(), BAD_REQUEST);
}
The controller:
#RestController
#RequestMapping(value = "/register", consumes = "application/json", produces = "application/json")
public class RegistrationController {
#Autowired
private RegistrationService registrationService;
#PostMapping(value = "/manager")
public ResponseEntity registerManager(#RequestBody #Valid Manager manager) {
registrationService.executeSelfUserRegistration(manager);
return new ResponseEntity<>(new Message("User " + manager.getEmailAddress() + " registered successfully!"), CREATED);
}
}
I get the 400 response code, but I am not seeing any response body containing the violated constraint messages.
After some more debugging, I found out that all constraint violations were wrapped into a MethodArgumentNotValidException (because of the #Valid annotations) - I had to dig a bit inside that exception to get my information.
I've overriden the handleMethodArgumentNotValid() method from ResponseEntityExceptionHandler and this is how I got it to work:
#Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
List<String> errorMessages = new ArrayList<>();
BindingResult bindingResult = ex.getBindingResult();
List<ObjectError> errors = bindingResult.getAllErrors();
for(ObjectError error : errors) {
String message = error.getDefaultMessage();
errorMessages.add(message);
}
return new ResponseEntity<>(new Error(errorMessages), new HttpHeaders(), BAD_REQUEST);
}
Maybe this helps someone.
When the target argument fails to pass the validation, Spring Boot throws a MethodArgumentNotValidException exception. I have extracted the error message from bindingResult of this exception as shown below:
#RestControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
#Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex, HttpHeaders headers,
HttpStatus status, WebRequest request) {
//to extract the default error message from a diagnostic
// information about the errors held in MethodArgumentNotValidException
Exception exception = new Exception(ex.getBindingResult().getAllErrors().get(0).getDefaultMessage());
return this.createResponseEntity(HttpStatus.BAD_REQUEST, exception, request);
}
private ResponseEntity<Object> createResponseEntity(
HttpStatus httpStatus, Exception ex, WebRequest request) {
ErrorResponse errorResponse = ErrorResponse.builder()
.timestamp(LocalDateTime.now())
.status(httpStatus.value())
.error(httpStatus.getReasonPhrase())
.message(ex.getMessage())
.path(request.getDescription(true))
.build();
return handleExceptionInternal(ex, errorResponse,
new HttpHeaders(), httpStatus, request);
}
}
ErrorResponse class:
#Data
#Builder
#NoArgsConstructor
#AllArgsConstructor
public class ErrorResponse {
private LocalDateTime timestamp;
private int status;
private String error;
private String message;
private String path;
}
The response will be 400 with body in JSON format as shown below:
{
"timestamp": "2021-01-20T10:30:15.011468",
"status": 400,
"error": "Bad Request",
"message": "Due date should not be greater than or equal to Repeat Until Date.",
"path": "uri=/api/tasks;client=172.18.0.5;user=109634489423695603526"
}
I hope this helps. If you need a detailed explanation on class-level constraint, have a look at this video.

Not able to return ResponseEntity with Exception Details in spring

I have created a Spring Restful Service and Spring MVC application.
Restful Service ::
Restful service returns an entity if its existing in DB. If it doesn't exist It returns a custom Exception information in ResponseEntity object.
It is working as expected tested using Postman.
#GetMapping(value = "/validate/{itemId}", produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE })
public ResponseEntity<MyItem> validateItem(#PathVariable Long itemId, #RequestHeader HttpHeaders httpHeaders) {
MyItem myItem = myitemService.validateMyItem(itemId);
ResponseEntity<MyItem> responseEntity = null;
if (myItem == null) {
throw new ItemNotFoundException("Item Not Found!!!!");
}
responseEntity = new ResponseEntity<MyItem>(myItem, headers, HttpStatus.OK);
return responseEntity;
}
If the requested Entity does not exist Restful Service returns below.
#ExceptionHandler(ItemNotFoundException.class)
public ResponseEntity<ExceptionResponse> itemNotFEx(WebRequest webRequest, Exception exception) {
System.out.println("In CREEH::ItemNFE");
ExceptionResponse exceptionResponse = new ExceptionResponse("Item Not Found Ex!!!", new Date(), webRequest.getDescription(false));
ResponseEntity<ExceptionResponse> responseEntity = new ResponseEntity<ExceptionResponse>(exceptionResponse, HttpStatus.NOT_FOUND);
return responseEntity;
}
But when I am calling the above service from a spring MVC application using RestTemplate, It is returning a valid object if it exists.
If the requested object does not exist Restful service is returning the exception information but its not reaching the calling(spring MVC) application.
Spring MVC application calls Restful Web Service using Rest template
String url = "http://localhost:8080/ItemServices/items/validate/{itemId}";
ResponseEntity<Object> responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, Object.class, uriParms);
int restCallStateCode = responseEntity.getStatusCodeValue();
This is expected behavior. Rest template throws exception when the http status is client error or server error and returns the response when http status is not error status.
You have to provide implementation to use your error handler, map the response to response entity and throw the exception.
Create new error exception class with ResponseEntity field.
public class ResponseEntityErrorException extends RuntimeException {
private ResponseEntity<ErrorResponse> errorResponse;
public ResponseEntityErrorException(ResponseEntity<ErrorResponse> errorResponse) {
this.errorResponse = errorResponse;
}
public ResponseEntity<ErrorResponse> getErrorResponse() {
return errorResponse;
}
}
Custom error handler which maps the error response back to ResponseEntity.
public class ResponseEntityErrorHandler implements ResponseErrorHandler {
private List<HttpMessageConverter<?>> messageConverters;
#Override
public boolean hasError(ClientHttpResponse response) throws IOException {
return hasError(response.getStatusCode());
}
protected boolean hasError(HttpStatus statusCode) {
return (statusCode.is4xxClientError() || statusCode.is5xxServerError());
}
#Override
public void handleError(ClientHttpResponse response) throws IOException {
HttpMessageConverterExtractor<ExceptionResponse> errorMessageExtractor =
new HttpMessageConverterExtractor(ExceptionResponse.class, messageConverters);
ExceptionResponse 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;
}
}
RestTemplate Configuration - You have to set RestTemplate's errorHandler to ResponseEntityErrorHandler.
#Configuration
public class RestTemplateConfiguration {
#Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
ResponseEntityErrorHandler errorHandler = new ResponseEntityErrorHandler();
errorHandler.setMessageConverters(restTemplate.getMessageConverters());
restTemplate.setErrorHandler(errorHandler);
return restTemplate;
}
}
Calling Method
#Autowired restTemplate
String url = "http://localhost:8080/ItemServices/items/validate/{itemId}";
try {
ResponseEntity<Object> responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, Object.class, uriParms);
int restCallStateCode = responseEntity.getStatusCodeValue();
} catch (ResponseEntityErrorException re) {
ResponseEntity<ErrorResponse> errorResponse = re.getErrorResponse();
}
Try using the #ResponseBody annotation on your Exceptionhandler. e.g:
public #ResponseBody ResponseEntity<ExceptionResponse> itemNotFEx(WebRequest webRequest, Exception exception) {... }
You should use Custom Exception Handler to fix your case. It looks like this
#ControllerAdvice
public class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
public CustomResponseEntityExceptionHandler() {
super();
}
// 404
#ExceptionHandler(value = { EntityNotFoundException.class, ResourceNotFoundException.class })
protected ResponseEntity<Object> handleNotFound(final RuntimeException ex, final WebRequest request) {
BaseResponse responseError = new BaseResponse(HttpStatus.NOT_FOUND.value(),HttpStatus.NOT_FOUND.name(),
Constants.HttpStatusMsg.ERROR_NOT_FOUND);
logger.error(ex.getMessage());
return handleExceptionInternal(ex, responseError, new HttpHeaders(), HttpStatus.NOT_FOUND, request);
}
}
And your code should throw some exception, eg:
if (your_entity == null) {
throw new EntityNotFoundException("said something");
}
If you get this case in somewhere else again, you just throw exception like above. Your handler will take care the rest stuffs.
Hope this help.
I've started your application and works just fine.
Maven :
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
The controller class is :
#Controller
public class ValidationController {
#GetMapping(value = "/validate/{itemId}")
public #ResponseBody ResponseEntity<MyItem> validateItem(#PathVariable Long itemId) {
if (itemId.equals(Long.valueOf(1))) {
throw new ItemNotFoundException();
}
return new ResponseEntity<>(new MyItem(), HttpStatus.OK);
}
#ExceptionHandler(ItemNotFoundException.class)
public ResponseEntity<ExceptionResponse> itemNotFEx(WebRequest webRequest, Exception exception) {
System.out.println("In CREEH::ItemNFE");
ExceptionResponse exceptionResponse = new ExceptionResponse("Item Not Found Ex!!!", new Date(), webRequest.getDescription(false));
ResponseEntity<ExceptionResponse> responseEntity = new ResponseEntity<>(exceptionResponse, HttpStatus.NOT_FOUND);
return responseEntity;
}
}
and the test:
#RunWith(SpringRunner.class)
#WebMvcTest(value = ValidationController.class, secure = false)
public class TestValidationController {
#Autowired
private MockMvc mockMvc;
#Test
public void testExpectNotFound() throws Exception {
mockMvc.perform(get("/validate/1"))
.andExpect(status().isNotFound());
}
#Test
public void testExpectFound() throws Exception {
mockMvc.perform(get("/validate/2"))
.andExpect(status().isOk());
}
}
Are you sure the url you are trying to use with RestTemplate is correct?
String url = "http://localhost:8080/ItemServices/items/validate/{itemId}";
Your get method is #GetMapping(value = "/validate/{itemId}"
If you don't have request mapping at the level of the controller the url should be:
http://localhost:8080/validate/1
Another difference is the missing #ResponseBody on your controller method.

Return HTTP code 200 from Spring REST API

I want to use this code to receive http link with values:
#PostMapping(value = "/v1/notification")
public String handleNotifications(#RequestParam("notification") String itemid) {
// parse here the values
return "result successful result";
}
How I can return http code 200 - successful response?
And also for example if there is a code exception into code processing how can I return error 404?
If you are using spring:
#PostMapping(value = "/v1/notification")
public ResponseEntity handleNotifications(#RequestParam("notification") String itemid) {
// parse here the values
return ResponseEntity.ok().build();
//OR ResponseEntity.ok("body goes here");
}
If you use #RestController it should return 200 by default.
But anyway, you can set a particular response status by #ResponseStatus annotation (even if the methods returns void) or you can return a custom response by ResponseEntity.
EDIT: added error handling
For error handling, you can return a particular response entity:
return ResponseEntity.status(HttpStatus.FORBIDDEN)
.body("some body ");
or you can use #ExceptionHandler:
#ExceptionHandler(Exception.class)
#ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public void handleError(Exception ex) {
// TODO: log exception
}
You can do it by annotating your method with #ResponseStatus using HttpStatus.OK (However it should be 200 by default), like this:
Some controller
#PostMapping(value = "/v1/notification")
#ResponseStatus(HttpStatus.OK)
public String handleNotifications(#RequestParam("notification") String itemid) throws MyException {
if(someCondition) {
throw new MyException("some message");
}
// parse here the values
return "result successful result";
}
Now, in order to return a custom code when handling a specific exception you can create a whole separate controller for doing this (you can do it in the same controller, though) which extends from ResponseEntityExceptionHandler and is annotated with #RestControllerAdvice and it must have a method for handling that specific exception as shown below:
Exception handling controller
#RestControllerAdvice
public class ExceptionHandlerController extends ResponseEntityExceptionHandler {
#ExceptionHandler(MyException.class)
protected ResponseEntity<Object> handleMyException(MyException ex, WebRequest req) {
Object resBody = "some message";
return handleExceptionInternal(ex, resBody, new HttpHeaders(), HttpStatus.NOT_FOUND, req);
}
}
You can do something like this:
#PostMapping(value = "/v1/notification")
public ResponseEntity<String> handleNotifications(
#RequestParam("notification") String itemid) {
// parse here the values
return new ResponseEntity<>("result successful result",
HttpStatus.OK);
}

customizing error response message when #requestparam is missing

I have already looked at a bunch of existing pages on stackoverflow for this but none of these helped:
How to customize #RequestParam error 400 response in Spring MVC
How to inform callers when required rquest parameter is missing?
My problem is extremely similar:
My application is really a REST api, returning json/xml data rather that html (ie I don't use jsps, but marshalling to transform java beans to json/xml)
When I query the URL with a required parameter, I get a 400 status with nothing in the payload, no text, nada.
I would like to return a json/xml payload using my ErrorResponse object that I use in other places.
I am using Spring 3.2.5
I have a controller which maps a URL to a method with a required
parameter(candidateBillDay)
#Controller
public class AccountController extends WsController {
private static final String JSP_CANDIDATE_PDD = "candidatepdd";
#RequestMapping( value="/account/{externalId}/{externalIdType}/candidatepdd"
, method = RequestMethod.GET)
public String getCandidatePaymentDueDateInfo( ModelMap model
, #PathVariable String externalId
, #PathVariable Integer externalIdType
, #RequestParam Integer candidateBillDay
, #RequestParam(required=false) Boolean includeCurrent ){
...
model.addAttribute( CandidatePaymentDueDateResponse.ROOT_ELEMENT, ...));
return JSP_CANDIDATE_PDD;
}
}
I have an exception handler that catches all types of exceptions, has some logic to do some specific bits for some types (instanceof):
#ControllerAdvice
public class BWSExceptionHandler extends ResponseEntityExceptionHandler {
private static final Logger LOG = LoggerFactory.getLogger(BWSExceptionHandler.class);
#ExceptionHandler(value = { Exception.class } )
public ResponseEntity<Object> handleOtherExceptions(final Exception ex, final WebRequest req) {
LOG.error("Uncaught Exception: ", ex);
ErrorResponse resp = null;
...
if( ex instanceof MissingServletRequestParameterException ){
MissingServletRequestParameterException e = (MissingServletRequestParameterException)ex;
resp = new ErrorResponse( Validatable.ERR_CODE_FIELD_NOT_POPULATED
, String.format( Validatable.MSG_FIELD_IS_REQUIRED
, e.getParameterName()
)
);
httpStatusCode = HttpStatus.BAD_REQUEST;
}
if(resp==null){
resp = new ErrorResponse(new ErrorElement("unknown_error", ex.getMessage()));
}
return handleExceptionInternal(ex, resp, new HttpHeaders(), httpStatusCode, req);
}
}
So this doesn't do anything when a parameter is missing. When I get an actual exception (ie account doesn't exist) then it does catch the exception and works as excepted. This leads me to think that no MissingServletRequestParameterException exception is thrown, which according to the doc, blogs and stackoverflow pages I've read should be thrown...
I have also tried implementing a class that extends DefaultHandlerExceptionResolver and override the handleMissingServletRequestParameter method with not much success ( following this blog: http://alexcuesta.wordpress.com/2011/05/11/error-handling-and-http-status-codes-with-spring-mvc/ )
Any idea of what I am doing wrong or what other option should I explore?
Try overriding handleMissingServletRequestParameter method in the BWSExceptionHandler class.
#ControllerAdvice
public class BWSExceptionHandler extends ResponseEntityExceptionHandler {
...
#Override
protected ResponseEntity<Object> handleMissingServletRequestParameter(
MissingServletRequestParameterException ex, HttpHeaders headers,
HttpStatus status, WebRequest request) {
// MissingServletRequestParameterException handling code goes here.
}
...
#ExceptionHandler(value = { Exception.class } )
public ResponseEntity<Object> handleOtherExceptions(final Exception ex,
final WebRequest req) {
...
}
}
Hope this helps.

Categories