@Override protected ResponseEntity<Object> handleMethodArgumentNotValid( MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { final List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors(); final List<ObjectError> globalErrors = ex.getBindingResult().getGlobalErrors(); StringBuilder errors = new StringBuilder(); for (FieldError fieldError : fieldErrors) { errors .append(fieldError.getField()) .append(": ") .append(fieldError.getDefaultMessage()) .append("\n"); } for (ObjectError globalError : globalErrors) { errors .append(globalError.getObjectName()) .append(": ") .append(globalError.getDefaultMessage()) .append("\n"); } return new ResponseEntity<>(errors.toString(), headers, status); }
public static void setJSONErrorMap(JSONBean<?> json, BindingResult result) { List<FieldError> fields = result.getFieldErrors(); for (FieldError field : fields) { System.out.println(field.getField() + ": " + field.getDefaultMessage()); json.getErrorMap().put(field.getField(), field.getDefaultMessage()); } }
@ResponseBody @RequestMapping(value = "/edit", method = RequestMethod.POST) public ImmutableMap<String, Object> linkEdit(@Valid Link link, BindingResult bindingResult) { if (bindingResult.hasErrors()) { Map<String, Object> errorMessage = Maps.newHashMap(); errorMessage.put("status", 0); List<FieldError> fes = bindingResult.getFieldErrors(); for (FieldError fe : fes) { errorMessage.put(fe.getField(), fe.getDefaultMessage()); } return ImmutableMap.<String, Object>builder().putAll(errorMessage).build(); } if (link.getLinkId() == null || link.getLinkId() == 0) { Link result = linkService.save(link); if (result == null || result.getLinkId() == null || result.getLinkId() == 0) { LOGGER.warn("内容链接失败,链接{}", result); return ImmutableMap.<String, Object>of( "status", "0", "message", getMessage("link.addfailed.message")); } LOGGER.info("内容添加成功,链接ID{}", result.getLinkId()); return ImmutableMap.<String, Object>of( "status", "1", "message", getMessage("link.addsuccess.message")); } try { linkService.save(link); } catch (Exception e) { LOGGER.error("链接修改失败,{}", e); return ImmutableMap.<String, Object>of( "status", "0", "message", getMessage("link.updatefailed.message")); } LOGGER.info("链接添加成功,{}", link); return ImmutableMap.<String, Object>of( "status", "1", "message", getMessage("link.updatesuccess.message")); }
@RequestMapping(value = "/bd_quick_reply", method = RequestMethod.PUT) @ResponseBody public Map<String, Object> update( @Valid QuickReply quickReply, Errors errors, Map<String, Object> map) { Map<String, Object> result = new HashMap<>(); if (errors.getErrorCount() > 0) { result.put("result", "error"); for (FieldError err : errors.getFieldErrors()) { map.put("err_" + err.getField(), err.getDefaultMessage()); } return result; } try { quickReplyService.update(quickReply); result.put("result", "success"); } catch (BusinessException e) { log.error(e.getMessage(), e); result.put("result", "error"); result.put("errorMsg", e.getMessage()); } return result; }
@ExceptionHandler(MethodArgumentNotValidException.class) @ResponseBody public ResponseEntity<ErrorMessage> handleValidationException(MethodArgumentNotValidException e) { List<ObjectError> errors = e.getBindingResult().getAllErrors(); List<String> messages = new ArrayList<String>(); // WebServiceError webServiceError = // WebServiceError.build(WebServiceError.Type.VALIDATION_ERROR, errors.get(0).getObjectName() + // " " + errors.get(0).getDefaultMessage()); for (ObjectError error : errors) { if (error instanceof FieldError) { FieldError fieldError = (FieldError) error; messages.add( fieldError.getField() + " " + fieldError.getRejectedValue() + " " + error.getDefaultMessage()); } else { messages.add(error.toString()); } } return new ResponseEntity<ErrorMessage>(new ErrorMessage(messages), HttpStatus.BAD_REQUEST); }
protected void testConstraintMessageCode( Constraint constraint, Object value, String code, Object[] args) { Errors errors = testConstraintFailed(constraint, value); FieldError fieldError = errors.getFieldError(constraint.getPropertyName()); checkCode(fieldError, code); checkArguments(args, fieldError.getArguments()); }
/** * méthode pour gérer les problèmes de validation de l'objet resource * * @param exception * @param response * @return */ @ExceptionHandler @ResponseBody public Map<String, Object> handleException(Exception exception, HttpServletResponse response) { LOGGER.error("Exception : ", exception); Map<String, Object> mapErrorMessage = new HashMap<>(); if (exception instanceof MethodArgumentNotValidException) { BindingResult result = ((MethodArgumentNotValidException) exception).getBindingResult(); List<FieldError> listFieldErrors = result.getFieldErrors(); for (FieldError fieldError : listFieldErrors) { mapErrorMessage.put(fieldError.getField(), fieldError.getDefaultMessage()); } response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } if (exception instanceof AccessDeniedException) { mapErrorMessage.put("Error : ", exception.getMessage()); response.setStatus(HttpServletResponse.SC_FORBIDDEN); } else if (exception instanceof ValidationException || exception instanceof HttpMessageNotReadableException || exception instanceof DataAccessException || exception instanceof MongoException || exception instanceof SocketTimeoutException || exception instanceof RuntimeException) { mapErrorMessage.put("Error : ", exception.getMessage()); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } LOGGER.error(mapErrorMessage.toString(), exception); return mapErrorMessage; }
@Test public void shouldAddErrorWhenEmptySourceIds() throws Exception { InvitationSentRecord record = InvitationSentRecord.toInvitationSentRecord("SLOTS", "IOS", ""); Errors errors = new BeanPropertyBindingResult(record, "record"); validator.validate(record, errors); FieldError fieldError = errors.getFieldError("sourceIds"); assertEquals("sourceIds must be present", fieldError.getDefaultMessage()); assertEquals("empty", fieldError.getCode()); }
protected void testConstraintMessageCodes( Constraint constraint, Object value, String[] code, Object[] args) { Errors errors = testConstraintFailed(constraint, value); FieldError fieldError = errors.getFieldError(constraint.getPropertyName()); for (int j = 0; j < code.length; j++) { checkCode(fieldError, code[j]); } checkArguments(args, fieldError.getArguments()); }
private ErrorDTO processFieldErrors(List<FieldError> fieldErrors) { ErrorDTO dto = new ErrorDTO(ErrorConstants.ERR_VALIDATION); for (FieldError fieldError : fieldErrors) { dto.add(fieldError.getObjectName(), fieldError.getField(), fieldError.getCode()); } return dto; }
public static List<KeyValuePair<String, String>> listErrors(BindingResult binding) { List<KeyValuePair<String, String>> errors = new ArrayList<KeyValuePair<String, String>>(); KeyValuePair<String, String> kvp; for (FieldError fe : binding.getFieldErrors()) { kvp = new KeyValuePair<String, String>(fe.getField(), fe.getDefaultMessage()); errors.add(kvp); } return errors; }
/** * Process the given JSR-303 ConstraintViolations, adding corresponding errors to the provided * Spring {@link Errors} object. * * @param violations the JSR-303 ConstraintViolation results * @param errors the Spring errors object to register to */ protected void processConstraintViolations( Set<ConstraintViolation<Object>> violations, Errors errors) { for (ConstraintViolation<Object> violation : violations) { String field = violation.getPropertyPath().toString(); FieldError fieldError = errors.getFieldError(field); if (fieldError == null || !fieldError.isBindingFailure()) { try { ConstraintDescriptor<?> cd = violation.getConstraintDescriptor(); String errorCode = cd.getAnnotation().annotationType().getSimpleName(); Object[] errorArgs = getArgumentsForConstraint(errors.getObjectName(), field, cd); if (errors instanceof BindingResult) { // Can do custom FieldError registration with invalid value from ConstraintViolation, // as necessary for Hibernate Validator compatibility (non-indexed set path in field) BindingResult bindingResult = (BindingResult) errors; String nestedField = bindingResult.getNestedPath() + field; if ("".equals(nestedField)) { String[] errorCodes = bindingResult.resolveMessageCodes(errorCode); bindingResult.addError( new ObjectError( errors.getObjectName(), errorCodes, errorArgs, violation.getMessage())); } else { Object invalidValue = violation.getInvalidValue(); if (!"".equals(field) && (invalidValue == violation.getLeafBean() || (field.contains(".") && !field.contains("[]")))) { // Possibly a bean constraint with property path: retrieve the actual property // value. // However, explicitly avoid this for "address[]" style paths that we can't handle. invalidValue = bindingResult.getRawFieldValue(field); } String[] errorCodes = bindingResult.resolveMessageCodes(errorCode, field); bindingResult.addError( new FieldError( errors.getObjectName(), nestedField, invalidValue, false, errorCodes, errorArgs, violation.getMessage())); } } else { // got no BindingResult - can only do standard rejectValue call // with automatic extraction of the current field value errors.rejectValue(field, errorCode, errorArgs, violation.getMessage()); } } catch (NotReadablePropertyException ex) { throw new IllegalStateException( "JSR-303 validated property '" + field + "' does not have a corresponding accessor for Spring data binding - " + "check your DataBinder's configuration (bean property versus direct field access)", ex); } } } }
/** * Check whether the given FieldError matches the given field. * * @param field the field that we are looking up FieldErrors for * @param fieldError the candidate FieldError * @return whether the FieldError matches the given field */ protected boolean isMatchingFieldError(String field, FieldError fieldError) { if (field.equals(fieldError.getField())) { return true; } // Optimization: use charAt instead of endsWith (SPR-11304) int endIndex = field.length() - 1; return (field.charAt(endIndex) == '*' && fieldError.getField().startsWith(field.substring(0, endIndex))); }
@Test public void shouldAddErrorWhenSourceIDIsBlank() { InvitationSentRecord record = InvitationSentRecord.toInvitationSentRecord("SLOTS", "IOS", ",1002222223"); Errors errors = new BeanPropertyBindingResult(record, "record"); validator.validate(record, errors); FieldError fieldError = errors.getFieldError("sourceIds"); assertEquals("sourceIds cannot be blank", fieldError.getDefaultMessage()); assertEquals("nullOrBlankSourceId", fieldError.getCode()); }
@Test public void shouldAddErrorWhenUnknownGame() throws Exception { InvitationSentRecord record = InvitationSentRecord.toInvitationSentRecord("BLACKJACK", "IOS", "*****@*****.**"); Errors errors = new BeanPropertyBindingResult(record, "record"); validator.validate(record, errors); FieldError fieldError = errors.getFieldError("gameType"); assertEquals("gameType is not supported", fieldError.getDefaultMessage()); assertEquals("unsupported", fieldError.getCode()); }
@ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public ErrorTester noRequestHandlerFoundExceptionHandler(MethodArgumentNotValidException e) { BindingResult result = e.getBindingResult(); FieldError error = result.getFieldError(); return new ErrorTester("There is error " + error.getDefaultMessage()); }
@Test public void shouldAddErrorWhenNullPlatform() throws Exception { InvitationSentRecord record = InvitationSentRecord.toInvitationSentRecord("SLOTS", null, "*****@*****.**"); Errors errors = new BeanPropertyBindingResult(record, "record"); validator.validate(record, errors); FieldError fieldError = errors.getFieldError("platform"); assertEquals("platform must be present", fieldError.getDefaultMessage()); assertEquals("empty", fieldError.getCode()); }
@Test public void shouldAddErrorWhenInvalidPlatform() throws Exception { InvitationSentRecord record = InvitationSentRecord.toInvitationSentRecord("SLOTS", "PLAYSTATION", "*****@*****.**"); Errors errors = new BeanPropertyBindingResult(record, "record"); validator.validate(record, errors); FieldError fieldError = errors.getFieldError("platform"); assertEquals("platform is not supported", fieldError.getDefaultMessage()); assertEquals("unsupported", fieldError.getCode()); }
@RequestMapping(value = "/register", method = RequestMethod.POST) public @ResponseBody UserJsonResponse handleRegistration( @Valid @RequestBody User user, BindingResult result, Locale locale, Model model, HttpServletRequest request) { logger.info(user.toString()); UserJsonResponse userJsonResponse = new UserJsonResponse(); if (request.getSession().getAttribute("loggedIn") != null) { userJsonResponse.setStatus("SUCCESS"); return userJsonResponse; } if (result.hasErrors()) { Map<String, String> errors = new HashMap<String, String>(); List<FieldError> fieldErrors = result.getFieldErrors(); for (FieldError fieldError : fieldErrors) { String[] resolveMessageCodes = result.resolveMessageCodes(fieldError.getCode()); String string = resolveMessageCodes[0]; // System.out.println("resolveMessageCodes : "+string); String message = messageSource.getMessage( string + "." + fieldError.getField(), new Object[] {fieldError.getRejectedValue()}, locale); // System.out.println("Meassage : "+message); errors.put(fieldError.getField(), message); } userJsonResponse.setStatus("ERROR"); userJsonResponse.setErrorsMap(errors); return userJsonResponse; } UserDAO userDao = (UserDAO) context.getBean("userDao"); if (userDao.get(user.getUsername()) != null) { return handleError(userJsonResponse, "username", locale); } else if (userDao.getUserBySerialNumber(user.getSerialNumber()) != null) { return handleError(userJsonResponse, "serialNumber", locale); } else { String hash = DaoHelper.getInstance().getPasswordHashing().getHashAndSalt(user.getPassword()); user.setHash(hash); user.setRole("Student"); Student student = new Student(user); student.setSubscriptionDate(new Date()); logger.info(student.toString()); userDao.create(student); userJsonResponse.setStatus("SUCCESS"); return userJsonResponse; } }
@ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public Map<String, String> handleValidationError(MethodArgumentNotValidException ex) { Map<String, String> fieldErrorMap = new HashMap<>(); BindingResult result = ex.getBindingResult(); List<FieldError> fieldErrors = result.getFieldErrors(); for (FieldError fieldError : fieldErrors) { fieldErrorMap.put(fieldError.getField(), fieldError.getDefaultMessage()); } return fieldErrorMap; }
@Override public boolean equals(Object other) { if (this == other) { return true; } if (!super.equals(other)) { return false; } FieldError otherError = (FieldError) other; return (getField().equals(otherError.getField()) && ObjectUtils.nullSafeEquals(getRejectedValue(), otherError.getRejectedValue()) && isBindingFailure() == otherError.isBindingFailure()); }
private boolean isErrorField() { if (errors == null) { return false; } for (FieldError err : errors) { if (err.getField().equals(field)) { return true; } } return false; }
private void handleFieldErrors(Exception e) { if (e.getCause() instanceof BindException) { BindException be = (BindException) e.getCause(); for (FieldError error : be.getFieldErrors()) { logger.error( String.format( "the value '%s' is not allowed for property '%s'", error.getRejectedValue(), error.getField())); } } else { e.printStackTrace(); } System.exit(1); }
/** Exception to be thrown when validation on an argument annotated with @Valid fails. */ @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<Map<String, Object>> handleMethodArgumentNotValidException( MethodArgumentNotValidException errors) { Map<String, Object> errorMap = new HashMap<String, Object>(); errorMap.put("hasErrors", "true"); errorMap.put("developerMessage", "There are validation issues, please provide valid inputs"); errorMap.put("userMessage", "Please provide valid inputs"); errorMap.put("moreInfo", errors.getMessage()); errorMap.put("errorCode", HttpStatus.BAD_REQUEST); errors.printStackTrace(); for (FieldError error : errors.getBindingResult().getFieldErrors()) { errorMap.put(error.getField(), error.getDefaultMessage()); } return new ResponseEntity<Map<String, Object>>(errorMap, HttpStatus.BAD_REQUEST); }
/** * Example Usage: * * <pre> * @Controller * class UserController { * @RequestMapping(value = "/userAjaxCheck.json", method = RequestMethod.POST) * public @ResponseBody ValidationResponse processFormAjaxJson(Model model, * @ModelAttribute(value = "user") @Valid User user, * BindingResult result) { * return AjaxValidationEngine.process(result); * } * } * </pre> * * @param result * @return */ public static ValidationResponse process(BindingResult result) { ValidationResponse res = new ValidationResponse(); if (!result.hasErrors()) { res.setStatus("SUCCESS"); } else { res.setStatus("FAIL"); List<FieldError> allErrors = result.getFieldErrors(); List<ErrorMessage> errorMesages = new ArrayList<ErrorMessage>(); for (FieldError objectError : allErrors) { errorMesages.add(new ErrorMessage(objectError.getField(), objectError.getDefaultMessage())); } res.setErrorMessageList(errorMesages); } return res; }
/** * Builds an error message from the web parameters binding result if there're errors. * * @param bindingResult * @return */ protected final String errorFromBindingResult(BindingResult bindingResult) { StringBuilder sb = new StringBuilder(); for (FieldError fe : bindingResult.getFieldErrors()) { Object rejectedVal = fe.getRejectedValue(); if (rejectedVal instanceof Object[]) { if (((Object[]) rejectedVal).length > 0) { rejectedVal = Arrays.toString((Object[]) rejectedVal); } else { rejectedVal = "empty array"; } } sb.append(fe.getField() + " was '" + rejectedVal + "'; " + fe.getDefaultMessage() + ". "); } return sb.toString(); }
public static BaseResponse createResponse(HttpStatus status, BindingResult result) { BaseResponse response = new BaseResponse(); if (result.hasErrors()) { response.setError(true); response.setHttpErrorCode(status.value()); /* create an array of total error count */ ArrayList<ErrorDTO> errors = new ArrayList<ErrorDTO>(result.getErrorCount()); /* append all field errors */ for (FieldError err : result.getFieldErrors()) { System.out.println( "I got field error for: " + err.getField() + ", message: " + err.getDefaultMessage() + ", code: " + err.getCode()); ErrorDTO dto = new ErrorDTO(err.getField(), err.getCode(), err.getDefaultMessage()); errors.add(dto); } /* append global errors now */ for (ObjectError err : result.getGlobalErrors()) { System.out.println( "I got global error for: " + err.getObjectName() + ", message: " + err.getDefaultMessage() + ", code: " + err.getCode()); ErrorDTO dto = new ErrorDTO(err.getObjectName(), err.getCode(), err.getDefaultMessage()); errors.add(dto); } response.setErrors(errors); } return response; }
@ExceptionHandler(InvalidRequestException.class) public ResponseEntity<Object> handleInvalidRequest(RuntimeException e, WebRequest request) { InvalidRequestException ire = (InvalidRequestException) e; List<FieldErrorResource> fieldErrorResources = new ArrayList<>(); List<FieldError> fieldErrors = ire.getErrors().getFieldErrors(); for (FieldError fieldError : fieldErrors) { FieldErrorResource fieldErrorResource = new FieldErrorResource(); fieldErrorResource.setResource(fieldError.getObjectName()); fieldErrorResource.setField(fieldError.getField()); fieldErrorResource.setCode(fieldError.getCode()); fieldErrorResource.setMessage(fieldError.getDefaultMessage()); fieldErrorResources.add(fieldErrorResource); } ErrorResource error = errorResource("InvalidRequest", ire.getMessage()); error.setFieldErrors(fieldErrorResources); return handleExceptionInternal( e, error, getHeaders(), HttpStatus.UNPROCESSABLE_ENTITY, request); }
private MessageDTO processFieldError(FieldError error) { MessageDTO message = null; if (error != null) { Locale currentLocale = LocaleContextHolder.getLocale(); String msg = msgSource.getMessage(error.getDefaultMessage(), null, currentLocale); ClientException clientException = new ClientException(RestErrorCodes.ERR_001, msg); message = new MessageDTO(MessageType.ERROR, clientException); } return message; }
private void checkCode(FieldError error, String code) { String[] codes = error.getCodes(); boolean result = false; for (int i = 0; i < codes.length; i++) { if (code.equals(codes[i])) { result = true; break; } } assertTrue("Code " + code + " is not found in error", result); }