handleConstraintViolationException in a controller advice

166 views Asked by At

I use spring boot 3, I search to centralize error handling about validation

public record RepoPubRecord(
        @NotEmpty(groups={Intranet.class,Extranet.class}
        Long idRepoPub,
        
        @NotEmpty(@NotEmpty(groups={Extranet.class})
        String pubSib,
        
        @NotNull(groups={Intranet.class,Extranet.class}
        PubRecord pub){
}

In a method of one of my service

public void update(Repo repot, RepoPubRecord repoPubRecord){

    Set<ConstraintViolation<RepoPubRecord>> violations = validator.validate(repoPubRecord, Extranet.class);

    if (!violations.isEmpty()) {
        throw new ConstraintViolationException(violations);
    }


    ....
}

I would like to manage this error globally

@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
    protected ResponseEntity<Object> handleMissingServletRequestParameter(MissingServletRequestParameterException ex, HttpHeaders headers,HttpStatus status, WebRequest request) {
        String error = ex.getParameterName() + " parameter is missing.";
        return new ResponseEntity<Object>(new MissingServletRequestParameterException(error, ex.getParameterType()), HttpStatus.BAD_REQUEST));
    }

    @ExceptionHandler(ConstraintViolationException.class)
    protected ResponseEntity<?> handleConstraintViolationException(ConstraintViolationException ex, HttpServletRequest request){
        try {
            Set<String> messages = ex.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.toSet());
            return new ResponseEntity<>(new ConstraintViolationException(messages), HttpStatus.BAD_REQUEST);
        } catch (Exception e) {
            return new ResponseEntity<>(new ConstraintViolationException<>(new HashSet<String>().add(ex.getMessage())), HttpStatus.INTERNAL_SERVER_ERROR);
        }

    }


}

I just don't understand what i'm suppoing to put in the ResponseEntity to get information of what has failed

0

There are 0 answers