0
0
Spring Bootframework~10 mins

Validation error responses in Spring Boot - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
Ausername
Bvalue
Cname
Dfield
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong variable name in the annotation.
Forgetting to add the annotation above the field.
2fill in blank
medium

Complete 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'
AValidationException
BMethodArgumentNotValidException
CException
DRuntimeException
Attempts:
3 left
💡 Hint
Common Mistakes
Using a generic Exception instead of the specific validation exception.
Mismatching the exception type in the method parameter.
3fill in blank
hard

Fix 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'
Aex
B1
C-1
D0
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.
4fill in blank
hard

Fill 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'
AtoMap
BgetDefaultMessage
CgetMessage
DtoList
Attempts:
3 left
💡 Hint
Common Mistakes
Using toList instead of toMap causes wrong collection type.
Using getMessage instead of getDefaultMessage returns less useful info.
5fill in blank
hard

Fill 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'
Aerrors
BHttpStatus
CBAD_REQUEST
DResponseEntity
Attempts:
3 left
💡 Hint
Common Mistakes
Using ResponseEntity instead of HttpStatus for the status argument.
Passing wrong variable as body.