0

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

robert trudel
  • 5,283
  • 17
  • 72
  • 124
  • What is your API format, does it expect json or something else? – SputNick Feb 01 '23 at 13:13
  • like 99.999% of the market on the web now... json – robert trudel Feb 01 '23 at 13:50
  • Ahh great, I suggest then you create an Error DTO class which will hold necessary information such as error name, error message and so on (the details which you need). Instantiate this object in your exception handler class, set the values and return that as the response entity. I would strongly urge you not to respond with the exception as the response body. Please refer the link for more info on this https://medium.com/@vidishapal/spring-boot-restful-global-exception-handling-50d7637bd267 – SputNick Feb 02 '23 at 08:16

0 Answers0