79278367

Date: 2024-12-13 12:49:59
Score: 0.5
Natty:
Report link

https://www.baeldung.com/spring-boot-bean-validation

@Entity
public class User {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;

@NotBlank(message = "Name is mandatory")
private String name;

@NotBlank(message = "Email is mandatory")
private String email;

// standard constructors / setters / getters / toString
 }

use of the @Valid annotation.

@RestController
public class UserController {

@PostMapping("/users")
ResponseEntity<String> addUser(@Valid @RequestBody User user) {
    // persisting the user
    return ResponseEntity.ok("User is valid");
}

// standard constructors / other methods

}

The @ExceptionHandler annotation allows us to handle specified types of exceptions through one single method.

@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public Map<String, String> handleValidationExceptions(
MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getAllErrors().forEach((error) -> {
    String fieldName = ((FieldError) error).getField();
    String errorMessage = error.getDefaultMessage();
    errors.put(fieldName, errorMessage);
});
return errors;

}

Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @Valid
  • User mentioned (0): @ExceptionHandler
  • Low reputation (1):
Posted by: Yusuf Koçak