Answers for "spring rest validation error handling"

0

spring rest validation error handling

/**
 * Method that check against {@code @Valid} Objects passed to controller endpoints
 *
 * @param exception
 * @return a {@code ErrorResponse}
 * @see com.aroussi.util.validation.ErrorResponse
 */
@ExceptionHandler(value=MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse handleException(MethodArgumentNotValidException exception) {

    List<ErrorModel> errorMessages = exception.getBindingResult().getFieldErrors().stream()
            .map(err -> new ErrorModel(err.getField(), err.getRejectedValue(), err.getDefaultMessage()))
            .distinct()
            .collect(Collectors.toList());
    return ErrorResponse.builder().errorMessage(errorMessages).build();
}
Posted by: Guest on August-10-2021

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language