spring rest validation error handling

Solutions on MaxInterview for spring rest validation error handling by the best coders in the world

showing results for - "spring rest validation error handling"
Elouise
04 May 2017
1/**
2 * Method that check against {@code @Valid} Objects passed to controller endpoints
3 *
4 * @param exception
5 * @return a {@code ErrorResponse}
6 * @see com.aroussi.util.validation.ErrorResponse
7 */
8@ExceptionHandler(value=MethodArgumentNotValidException.class)
9@ResponseStatus(HttpStatus.BAD_REQUEST)
10public ErrorResponse handleException(MethodArgumentNotValidException exception) {
11
12    List<ErrorModel> errorMessages = exception.getBindingResult().getFieldErrors().stream()
13            .map(err -> new ErrorModel(err.getField(), err.getRejectedValue(), err.getDefaultMessage()))
14            .distinct()
15            .collect(Collectors.toList());
16    return ErrorResponse.builder().errorMessage(errorMessages).build();
17}
18