Spring Controller will throw TypeMismatchException
for your case.
To handle any exception at controller level you can annotate the method with @ExceptionHandler
Something like this
@ExceptionHandler(TypeMismatchException.class)
@ResponseBody
public SampleObject handleTypeMismatchException(TypeMismatchException typeMismatchException) {
...
}
You can also configure Global Exception Handling With @ControllerAdvice.
@ControllerAdvice
public class GlobalExceptionHandler {
/** Provides handling for exceptions throughout this service. */
@ExceptionHandler({ TypeMismatchException.class })
public final ResponseEntity<ApiError> handleException(Exception ex, WebRequest request) {
HttpHeaders headers = new HttpHeaders();
HttpStatus status = HttpStatus.BAD_REQUEST;
TypeMismatchException tme = (TypeMismatchException) ex;
return handleTypeMismatchException(tme, headers, status, request);
}
/** Customize the response for TypeMismatchException. */
protected ResponseEntity<ApiError> handleTypeMismatchException(TypeMismatchException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
List<String> errorMessages = ex.getErrors()
.stream()
.map(contentError -> contentError.getObjectName() + " " + contentError.getDefaultMessage())
.collect(Collectors.toList());
return handleExceptionInternal(ex, new ApiError(errorMessages), headers, status, request);
}
/** A single place to customize the response body of all Exception types. */
protected ResponseEntity<ApiError> handleExceptionInternal(Exception ex, ApiError body, HttpHeaders headers, HttpStatus status, WebRequest request) {
if (HttpStatus.INTERNAL_SERVER_ERROR.equals(status)) {
request.setAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE, ex, WebRequest.SCOPE_REQUEST);
}
return new ResponseEntity<>(body, headers, status);
}
}