RestErrorHandler { @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public RestError handleValidationError(MethodArgumentNotValidException ex) { LOGGER.info("Handling validation error"); RestError.Builder error = RestError.getBuilder() .status(HttpStatus.BAD_REQUEST) .code(HttpStatus.BAD_REQUEST.value()) .message(ex.getMessage()); List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors(); for (FieldError fieldError: fieldErrors) { error.validationError(fieldError.getField(), fieldError.getCode(), fieldError.getDefaultMessage()); } RestError validationError = error.build(); LOGGER.info("Returning validation error: {}", validationError); return validationError; }  @ExceptionHandler(TodoNotFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) void handleTodoNotFound(TodoNotFoundException ex); @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody RestError handleValidationError(MethodArgumentNotValidException ex);  }
@Test public void handleValidationError_WithOneFieldError_ShouldReturnRestErrorWithOneValidationError() throws NoSuchMethodException { MethodParameter invokedMethod = createInvokedMethod(); FieldError fieldValidationError = createFieldError(FIELD_NAME, FIELD_ERROR_CODE, FIELD_ERROR_DEFAULT_MESSAGE); BindingResult bindingResult = new BeanPropertyBindingResult(new Object(), OBJECT_NAME); bindingResult.addError(fieldValidationError); MethodArgumentNotValidException ex = new MethodArgumentNotValidException(invokedMethod, bindingResult); RestError error = errorHandler.handleValidationError(ex); assertThat(error.getCode()).isEqualTo(HttpStatus.BAD_REQUEST.value()); assertThat(error.getMessage()).isNotEmpty(); assertThat(error.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST); List<ValidationError> validationErrors = error.getValidationErrors(); assertThat(validationErrors).hasSize(1); ValidationError validationError = validationErrors.get(0); assertThat(validationError.getField()).isEqualTo(FIELD_NAME); assertThat(validationError.getErrorCode()).isEqualTo(FIELD_ERROR_CODE); assertThat(validationError.getErrorMessage()).isEqualTo(FIELD_ERROR_DEFAULT_MESSAGE); }