I am developing a RESTful app using Spring4. I want to handle the case when a POST request contains no body. I wrote the following custom exception handler:
@ControllerAdvice
public class MyRestExceptionHandler {
@ExceptionHandler
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseEntity<MyErrorResponse> handleJsonMappingException(JsonMappingException ex) {
MyErrorResponse errorResponse = new MyErrorResponse("request has empty body");
return new ResponseEntity<MyErrorResponse>(errorResponse, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(Throwable.class)
public ResponseEntity<MyErrorResponse> handleDefaultException(Throwable ex) {
MyErrorResponse errorResponse = new MyErrorResponse(ex);
return new ResponseEntity<MyErrorResponse>(errorResponse, HttpStatus.BAD_REQUEST);
}
}
@RestController
public class ContactRestController{
@RequestMapping(path="/contact", method=RequestMethod.POST)
public void save(@RequestBody ContactDTO contactDto) {...}
}
When it receives a POST with no body, these methods aren't called. Instead, the client gets a response with 400 BAD REQUEST HTTP status and empty body. Does anybody know how to handle it?
@ExceptionHandler(JsonMappingException.class)
? – Devest