下面列出了org.springframework.web.bind.annotation.ExceptionHandler#org.springframework.web.bind.MethodArgumentNotValidException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) {
BindingResult result = ex.getBindingResult();
List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream()
.map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode()))
.collect(Collectors.toList());
Problem problem = Problem.builder()
.withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE)
.withTitle("Method argument not valid")
.withStatus(defaultConstraintViolationStatus())
.with("message", ErrorConstants.ERR_VALIDATION)
.with("fieldErrors", fieldErrors)
.build();
return create(ex, problem, request);
}
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers, HttpStatus status,
WebRequest request) {
List<String> globalErrors = ex.getBindingResult().getGlobalErrors()
.stream()
.map(error -> error.getObjectName() + ": " + error.getDefaultMessage())
.collect(toList());
List<ApiResourcePropertyError> fieldErrors = ex.getBindingResult().getFieldErrors()
.stream()
.map(this::toResourcePropertyError)
.collect(toList());
ApiError apiError = ApiError.builder()
.message("Validation error")
.status(ex.getParameter().hasParameterAnnotation(RequestBody.class) ? HttpStatus.UNPROCESSABLE_ENTITY : HttpStatus.BAD_REQUEST)
.details(Stream.concat(globalErrors.stream(), fieldErrors.stream()).collect(toList()))
.build();
return handleExceptionInternal(ex, apiError, headers, apiError.getStatus(), request);
}
@Test
@Parameters(method = "provideValidationParams")
public void validationException_ShouldBeHandledProperly(Object pojo, Locale locale, CodedMessage... codedMessages) {
contextRunner.run(ctx -> {
WebErrorHandlers errorHandlers = ctx.getBean(WebErrorHandlers.class);
Validator validator = ctx.getBean(Validator.class);
BindingResult result = new BeanPropertyBindingResult(pojo, "pojo");
validator.validate(pojo, result);
// Assertions for BindException
HttpError bindError = errorHandlers.handle(new BindException(result), null, locale);
assertThat(bindError.getHttpStatus()).isEqualTo(HttpStatus.BAD_REQUEST);
assertThat(bindError.getErrors()).containsOnly(codedMessages);
// Assertions for MethodArgumentNotValidException
HttpError argumentError = errorHandlers.handle(new MethodArgumentNotValidException(mock(MethodParameter.class), result), null, locale);
assertThat(argumentError.getHttpStatus()).isEqualTo(HttpStatus.BAD_REQUEST);
assertThat(argumentError.getErrors()).containsOnly(codedMessages);
verifyPostProcessorsHasBeenCalled(ctx);
});
}
private Object exeute(HttpServletRequest reqest, HttpServletResponse response, Exception e) {
log.error(StringUtil.getMessage(e), e);
//if (isAjax(reqest)) {
String exMsg = StringUtil.getMessage(e);
if (e instanceof InvocationTargetException && exMsg == null) {
exMsg = ((InvocationTargetException) e).getTargetException().getMessage();
} else if (e instanceof MethodArgumentNotValidException) {
List<String> list = StringUtil.toList(exMsg, "default message");
if (CollectionUtils.isNotEmpty(list) && list.size() > 1) {
List<FieldError> errors = ((MethodArgumentNotValidException) e).getBindingResult().getFieldErrors();
if (CollectionUtils.isNotEmpty(list)) {
exMsg = errors.get(0).getDefaultMessage();
}
}
}
if (exMsg == null) {
exMsg = e.toString();
}
return ServiceResult.fail(exMsg);
/* } else {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("/err/500/index.html");
return modelAndView;
}*/
}
@Test
@Parameters(method = "provideParamsForHandle")
public void handle_ShouldHandleTheValidationErrorsProperly(Object toValidate,
Set<String> errorCodes,
Map<String, List<Argument>> args) {
BindingResult result = new BeanPropertyBindingResult(toValidate, "toValidate");
validator.validate(toValidate, result);
// Create and assert for BindException
BindException bindException = new BindException(result);
HandledException handledForBind = handler.handle(bindException);
assertThat(handledForBind.getErrorCodes()).containsAll(errorCodes);
assertThat(handledForBind.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
assertThat(handledForBind.getArguments()).isEqualTo(args);
// Create and assert for MethodArgumentNotValidException
MethodArgumentNotValidException exception = new MethodArgumentNotValidException(null, result);
HandledException handled = handler.handle(exception);
assertThat(handled.getErrorCodes()).containsAll(errorCodes);
assertThat(handled.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
assertThat(handled.getArguments()).isEqualTo(args);
}
@Override
public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) {
BindingResult result = ex.getBindingResult();
List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream()
.map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode()))
.collect(Collectors.toList());
Problem problem = Problem.builder()
.withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE)
.withTitle("Method argument not valid")
.withStatus(defaultConstraintViolationStatus())
.with("message", ErrorConstants.ERR_VALIDATION)
.with("fieldErrors", fieldErrors)
.build();
return create(ex, problem, request);
}
@Override
public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) {
BindingResult result = ex.getBindingResult();
List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream()
.map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode()))
.collect(Collectors.toList());
Problem problem = Problem.builder()
.withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE)
.withTitle("Method argument not valid")
.withStatus(defaultConstraintViolationStatus())
.with("message", ErrorConstants.ERR_VALIDATION)
.with("fieldErrors", fieldErrors)
.build();
return create(ex, problem, request);
}
@Test
public void processValidationErrorTest() throws Exception {
UserJWTController control = new UserJWTController(null, null);
MockMvc jwtMock = MockMvcBuilders.standaloneSetup(control)
.setControllerAdvice(new ExceptionTranslator())
.build();
MvcResult res = jwtMock.perform(post("/api/authenticate")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.accept(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN, MediaType.ALL)
.content("{\"username\":\"fakeUsernameTooLongfakeUsernameTooLongfakeUsernameTooLongfakeUsernameTooLong" +
"\",\"password\":\"fakePassword\",\"rememberMe\":false}"))
.andExpect(status().isBadRequest())
.andReturn();
assertThat(res.getResolvedException(), instanceOf(MethodArgumentNotValidException.class));
}
/**
* JSR303参数校验错误
* @param ex BindException
*/
@ExceptionHandler({BindException.class,MethodArgumentNotValidException.class})
public JsonData<Void> bindException(MethodArgumentNotValidException ex) {
LogBack.error(ex.getMessage(), ex);
BindingResult bindingResult = ex.getBindingResult();
if (bindingResult.hasErrors()) {
List<FieldError> errors = bindingResult.getFieldErrors();
List<ValidFieldError> validList = new ArrayList<>();
if (!(CollectionUtils.isEmpty(errors))) {
for (FieldError fe : errors) {
validList.add(new ValidFieldError(fe));
}
}
LogBack.error("参数校验错误:" + validList.toString(), ex);
return JsonData.failed(StatusEnum.PARAM_INVALID, validList.toString());
}
return JsonData.failed(StatusEnum.PARAM_INVALID);
}
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers,
HttpStatus status, WebRequest request) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("timestamp", new Date());
body.put("status", status.value());
//Get all errors
List<String> errors = ex.getBindingResult()
.getFieldErrors()
.stream()
.map(x -> x.getDefaultMessage())
.collect(Collectors.toList());
body.put("errors", errors);
return new ResponseEntity<>(body, headers, status);
//Map<String, String> fieldErrors = ex.getBindingResult().getFieldErrors().stream().collect(
// Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
}
@Override
public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) {
BindingResult result = ex.getBindingResult();
List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream()
.map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode()))
.collect(Collectors.toList());
Problem problem = Problem.builder()
.withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE)
.withTitle("Method argument not valid")
.withStatus(defaultConstraintViolationStatus())
.with(MESSAGE_KEY, ErrorConstants.ERR_VALIDATION)
.with(FIELD_ERRORS_KEY, fieldErrors)
.build();
return create(ex, problem, request);
}
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers,
HttpStatus status, WebRequest request) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("timestamp", new Date());
body.put("status", status.value());
//Get all errors
List<String> errors = ex.getBindingResult()
.getFieldErrors()
.stream()
.map(x -> x.getDefaultMessage())
.collect(Collectors.toList());
body.put("errors", errors);
return new ResponseEntity<>(body, headers, status);
//Map<String, String> fieldErrors = ex.getBindingResult().getFieldErrors().stream().collect(
// Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
}
@ExceptionHandler(value = Exception.class)
public Result exceptionHandler(Exception e) {
String message = null;
if (e instanceof IllegalArgumentException) {
message = "传入了错误的参数";
}
if (e instanceof MethodArgumentNotValidException) {
message = ((MethodArgumentNotValidException) e).getBindingResult().getFieldError().getDefaultMessage();
}
if (e instanceof UnauthorizedException) {
message = "权限认证失败";
}
return ResultFactory.buildFailResult(message);
}
/**
* IllegalArgumentException异常处理返回json
* 返回状态码:500
*/
@ResponseStatus(HttpStatus.OK)
@ExceptionHandler({MethodArgumentNotValidException.class})
public JSONResult argumentNotValidException(MethodArgumentNotValidException e) {
List<FieldError> bindingResult = e.getBindingResult().getFieldErrors();
StringBuilder sb = new StringBuilder();
//请求参数错误
sb.append(ErrorEnum.ERROR_PARAM.getErrorMessage()).append(" --> ");
for (FieldError fieldError : bindingResult) {
sb.append(fieldError.getField());
sb.append(" : ");
sb.append(fieldError.getDefaultMessage());
sb.append(" ; ");
}
return defHandler(null, sb.toString(), e);
}
@Override
public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) {
BindingResult result = ex.getBindingResult();
List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream()
.map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode()))
.collect(Collectors.toList());
Problem problem = Problem.builder()
.withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE)
.withTitle("Method argument not valid")
.withStatus(defaultConstraintViolationStatus())
.with(MESSAGE_KEY, ErrorConstants.ERR_VALIDATION)
.with(FIELD_ERRORS_KEY, fieldErrors)
.build();
return create(ex, problem, request);
}
@Override
public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) {
BindingResult result = ex.getBindingResult();
List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream()
.map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode()))
.collect(Collectors.toList());
Problem problem = Problem.builder()
.withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE)
.withTitle("Method argument not valid")
.withStatus(defaultConstraintViolationStatus())
.with(MESSAGE_KEY, ErrorConstants.ERR_VALIDATION)
.with(FIELD_ERRORS_KEY, fieldErrors)
.build();
return create(ex, problem, request);
}
@Override
public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) {
BindingResult result = ex.getBindingResult();
List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream()
.map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode()))
.collect(Collectors.toList());
Problem problem = Problem.builder()
.withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE)
.withTitle("Method argument not valid")
.withStatus(defaultConstraintViolationStatus())
.with(MESSAGE_KEY, ErrorConstants.ERR_VALIDATION)
.with(FIELD_ERRORS_KEY, fieldErrors)
.build();
return create(ex, problem, request);
}
@Override
public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) {
BindingResult result = ex.getBindingResult();
List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream()
.map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode()))
.collect(Collectors.toList());
Problem problem = Problem.builder()
.withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE)
.withTitle("Method argument not valid")
.withStatus(defaultConstraintViolationStatus())
.with(MESSAGE_KEY, ErrorConstants.ERR_VALIDATION)
.with(FIELD_ERRORS_KEY, fieldErrors)
.build();
return create(ex, problem, request);
}
@Override
public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) {
BindingResult result = ex.getBindingResult();
List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream()
.map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode()))
.collect(Collectors.toList());
Problem problem = Problem.builder()
.withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE)
.withTitle("Method argument not valid")
.withStatus(defaultConstraintViolationStatus())
.with("message", ErrorConstants.ERR_VALIDATION)
.with("fieldErrors", fieldErrors)
.build();
return create(ex, problem, request);
}
@Override
public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) {
BindingResult result = ex.getBindingResult();
List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream()
.map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode()))
.collect(Collectors.toList());
Problem problem = Problem.builder()
.withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE)
.withTitle("Method argument not valid")
.withStatus(defaultConstraintViolationStatus())
.with("message", ErrorConstants.ERR_VALIDATION)
.with("fieldErrors", fieldErrors)
.build();
return create(ex, problem, request);
}
@Override
public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) {
BindingResult result = ex.getBindingResult();
List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream()
.map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode()))
.collect(Collectors.toList());
Problem problem = Problem.builder()
.withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE)
.withTitle("Method argument not valid")
.withStatus(defaultConstraintViolationStatus())
.with("message", ErrorConstants.ERR_VALIDATION)
.with("fieldErrors", fieldErrors)
.build();
return create(ex, problem, request);
}
@Override
public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) {
BindingResult result = ex.getBindingResult();
List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream()
.map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode()))
.collect(Collectors.toList());
Problem problem = Problem.builder()
.withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE)
.withTitle("Method argument not valid")
.withStatus(defaultConstraintViolationStatus())
.with("message", ErrorConstants.ERR_VALIDATION)
.with("fieldErrors", fieldErrors)
.build();
return create(ex, problem, request);
}
@Override
public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) {
BindingResult result = ex.getBindingResult();
List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream()
.map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode()))
.collect(Collectors.toList());
Problem problem = Problem.builder()
.withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE)
.withTitle("Method argument not valid")
.withStatus(defaultConstraintViolationStatus())
.with("message", ErrorConstants.ERR_VALIDATION)
.with("fieldErrors", fieldErrors)
.build();
return create(ex, problem, request);
}
@Override
public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) {
BindingResult result = ex.getBindingResult();
List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream()
.map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode()))
.collect(Collectors.toList());
Problem problem = Problem.builder()
.withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE)
.withTitle("Method argument not valid")
.withStatus(defaultConstraintViolationStatus())
.with("message", ErrorConstants.ERR_VALIDATION)
.with("fieldErrors", fieldErrors)
.build();
return create(ex, problem, request);
}
@Override
public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) {
BindingResult result = ex.getBindingResult();
List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream()
.map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode()))
.collect(Collectors.toList());
Problem problem = Problem.builder()
.withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE)
.withTitle("Method argument not valid")
.withStatus(defaultConstraintViolationStatus())
.with("message", ErrorConstants.ERR_VALIDATION)
.with("fieldErrors", fieldErrors)
.build();
return create(ex, problem, request);
}
@Override
public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) {
BindingResult result = ex.getBindingResult();
List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream()
.map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode()))
.collect(Collectors.toList());
Problem problem = Problem.builder()
.withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE)
.withTitle("Method argument not valid")
.withStatus(defaultConstraintViolationStatus())
.with("message", ErrorConstants.ERR_VALIDATION)
.with("fieldErrors", fieldErrors)
.build();
return create(ex, problem, request);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
public DataResponse<List<FieldErrorDTO>> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
DataResponse<List<FieldErrorDTO>> response
= new DataResponse<>(translator.translate(ResultCode.ILLEGAL_ARGUMENT));
BindingResult bindingResult = e.getBindingResult();
if (bindingResult.hasErrors()) {
List<FieldErrorDTO> fieldErrorDTOList = new LinkedList<>();
bindingResult.getFieldErrors().forEach(fieldError -> {
FieldErrorDTO fieldErrorDTO = new FieldErrorDTO();
fieldErrorDTO.setField(fieldError.getField());
fieldErrorDTO.setErrorInfo(fieldError.getDefaultMessage());
fieldErrorDTOList.add(fieldErrorDTO);
});
response.setData(fieldErrorDTOList);
}
logger.warn("{}", response, e);
return response;
}
@Override
public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) {
BindingResult result = ex.getBindingResult();
List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream()
.map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode()))
.collect(Collectors.toList());
Problem problem = Problem.builder()
.withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE)
.withTitle("Method argument not valid")
.withStatus(defaultConstraintViolationStatus())
.with("message", ErrorConstants.ERR_VALIDATION)
.with("fieldErrors", fieldErrors)
.build();
return create(ex, problem, request);
}
/**
* Throws MethodArgumentNotValidException if validation fails.
* @throws HttpMessageNotReadableException if {@link RequestBody#required()}
* is {@code true} and there is no body content or if there is no suitable
* converter to read the content with.
*/
@Override
public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {
parameter = parameter.nestedIfOptional();
Object arg = readWithMessageConverters(webRequest, parameter, parameter.getNestedGenericParameterType());
String name = Conventions.getVariableNameForParameter(parameter);
if (binderFactory != null) {
WebDataBinder binder = binderFactory.createBinder(webRequest, arg, name);
if (arg != null) {
validateIfApplicable(binder, parameter);
if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) {
throw new MethodArgumentNotValidException(parameter, binder.getBindingResult());
}
}
if (mavContainer != null) {
mavContainer.addAttribute(BindingResult.MODEL_KEY_PREFIX + name, binder.getBindingResult());
}
}
return adaptArgumentIfNecessary(arg, parameter);
}
/**
* 处理所有接口数据验证异常
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ApiError> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
// 打印堆栈信息
log.error(ThrowableUtil.getStackTrace(e));
String[] str = Objects.requireNonNull(e.getBindingResult().getAllErrors().get(0).getCodes())[1].split("\\.");
String message = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
String msg = "不能为空";
if (msg.equals(message)) {
message = str[1] + ":" + message;
}
return buildResponseEntity(ApiError.error(message));
}