Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to add validation to the 'name' field using annotations.
Spring Boot
@NotBlank(message = "Name is required") private String [1];
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong variable name in the annotation.
Forgetting to add the annotation above the field.
✗ Incorrect
The field to validate is named 'name', so the annotation applies to 'name'.
2fill in blank
mediumComplete the code to handle validation errors by returning a bad request response.
Spring Boot
@ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<String> handleValidationException([1] ex) { return ResponseEntity.badRequest().body("Validation failed"); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a generic Exception instead of the specific validation exception.
Mismatching the exception type in the method parameter.
✗ Incorrect
The exception handler must catch MethodArgumentNotValidException to handle validation errors.
3fill in blank
hardFix the error in extracting the first validation error message from the exception.
Spring Boot
String errorMessage = ex.getBindingResult().getFieldErrors().get([1]).getDefaultMessage(); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using index 1 which causes IndexOutOfBoundsException if only one error exists.
Using -1 which is invalid for list indexing.
✗ Incorrect
The first error is at index 0 in the list of field errors.
4fill in blank
hardFill both blanks to create a map of field names to error messages from validation errors.
Spring Boot
Map<String, String> errors = ex.getBindingResult().getFieldErrors().stream()
.collect(Collectors.[1](error -> error.getField(), error -> error.[2]())); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using toList instead of toMap causes wrong collection type.
Using getMessage instead of getDefaultMessage returns less useful info.
✗ Incorrect
toMap collects entries into a map; getDefaultMessage gets the error message string.
5fill in blank
hardFill all three blanks to return a ResponseEntity with the error map and HTTP status BAD_REQUEST.
Spring Boot
return new ResponseEntity<>([1], [2].[3]);
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using ResponseEntity instead of HttpStatus for the status argument.
Passing wrong variable as body.
✗ Incorrect
The body is 'errors', status is HttpStatus.BAD_REQUEST for validation failure.