Complete the code to annotate a field for validation.
public class User { @[1](message = "Name cannot be empty") private String name; }
The @NotNull annotation ensures the field is not null, which is a basic validation for required fields.
Complete the code to handle validation errors in a controller advice.
@RestControllerAdvice public class ValidationExceptionHandler { @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<Map<String, String>> handleValidationExceptions( [1] ex) { Map<String, String> errors = new HashMap<>(); ex.getBindingResult().getFieldErrors().forEach(error -> errors.put(error.getField(), error.getDefaultMessage())); return ResponseEntity.badRequest().body(errors); } }
The MethodArgumentNotValidException is thrown when validation on an argument annotated with @Valid fails.
Fix the error in the code to extract field errors correctly.
ex.getBindingResult().get[1]().forEach(error ->
errors.put(error.getField(), error.getDefaultMessage()));The correct method is getFieldErrors() which returns a list of field errors.
Fill both blanks to create a custom error response class with fields for message and timestamp.
public class ErrorResponse { private String [1]; private LocalDateTime [2]; public ErrorResponse(String message, LocalDateTime timestamp) { this.message = message; this.timestamp = timestamp; } // getters and setters }
The fields should be named message and timestamp to match the constructor and common naming conventions.
Fill all three blanks to build a method that returns a formatted error response with HTTP status and body.
public ResponseEntity<ErrorResponse> buildErrorResponse(String [1], HttpStatus [2]) { ErrorResponse errorResponse = new ErrorResponse([1], LocalDateTime.now()); return ResponseEntity.status([2]).body(errorResponse); }
The method uses message as the error text parameter and status as the HTTP status. These are used to create the response entity.