View Javadoc
1   package cn.home1.oss.lib.errorhandle.internal.resolver;
2   
3   import static com.google.common.collect.Lists.newLinkedList;
4   
5   import cn.home1.oss.lib.errorhandle.api.AbstractConcreteExceptionResolver;
6   import cn.home1.oss.lib.errorhandle.api.ValidationError;
7   
8   import org.springframework.validation.BindingResult;
9   import org.springframework.validation.FieldError;
10  import org.springframework.validation.ObjectError;
11  import org.springframework.web.bind.MethodArgumentNotValidException;
12  
13  import java.util.List;
14  import java.util.Optional;
15  
16  public class MethodArgumentNotValidExceptionResolver //
17    extends AbstractConcreteExceptionResolver<MethodArgumentNotValidException> {
18  
19    @Override
20    public Optional<List<ValidationError>> validationErrors(final MethodArgumentNotValidException exception) {
21      final List<ValidationError> validationErrors = newLinkedList();
22  
23      final BindingResult bindingResult = exception.getBindingResult();
24      for (final ObjectError err : bindingResult.getGlobalErrors()) {
25        validationErrors.add(ValidationError.validationErrorBuilder() //
26          .message(err.getDefaultMessage()) //
27          .build() //
28        );
29      }
30      for (final FieldError err : bindingResult.getFieldErrors()) {
31        final Object rejectedValue = err.getRejectedValue();
32        final String rejected = rejectedValue != null ? rejectedValue.toString() : null;
33        validationErrors.add(ValidationError.validationErrorBuilder() //
34          .field(err.getField()) //
35          .rejected(rejected) //
36          .message(err.getDefaultMessage()) //
37          .build() //
38        );
39      }
40  
41      return Optional.of(validationErrors);
42    }
43  }