For the Page Number if someone has entered "test" , I want to customise the error message "Please provide the correct type for the parameter : pageNo"
.
Request Object:
{
"pageSize":6,
"pageNo":"test",
"sortBy": "lastModifiedTime"
}
How do i determine the the parameter which caused the exception :
@ExceptionHandler({ HttpMessageNotReadableException.class, HttpMediaTypeNotSupportedException.class,
HttpMessageNotWritableException.class,
ConversionNotSupportedException.class })
public ResponseEntity<RestResponse> handleRequestErrors(final Exception ex) {
RestResponse response = new RestResponse();
response.setCode(HttpStatus.BAD_REQUEST.value());
response.setStatus(false);
response.setMsg(ex.getMessage());
if (ex instanceof HttpMediaTypeNotSupportedException
|| ex instanceof HttpMessageNotWritableException
|| ex instanceof HttpMessageNotReadableException) {
response.setMsgCode(AppCode.E_GEN_CONTENT_TYPE_NOT_SUPPORTED);
}
return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
}
The same scenario can be handled for the query param validation :
Controller Advice :
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
@ResponseBody
public ResponseEntity<RestResponse> handleMethodArgumentTypeMismatchException(HttpServletRequest request,
MethodArgumentTypeMismatchException exception) {
RestResponse response = new RestResponse();
response.setCode(HttpStatus.BAD_REQUEST.value()); // 400
response.setStatus(false);
response.setMsgCode(AppStrings.BAD_REQUEST);
String param = exception.getName();
response.setMsg("Please provide the correct type for the parameter : " + param);
return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
}
Controller Class :
public ResponseEntity<RestResponse> getNotifications(
@RequestParam(defaultValue = "0") @Min(0) IntegerpageNo,
@RequestParam(defaultValue = "5") @Min(1) Integer pageSize,
@RequestParam(defaultValue = "lastModifiedTime") String sortBy) {