Java Code Examples for org.springframework.validation.FieldError#getField()

The following examples show how to use org.springframework.validation.FieldError#getField() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: EscapedErrors.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Nullable
private <T extends ObjectError> T escapeObjectError(@Nullable T source) {
	if (source == null) {
		return null;
	}
	String defaultMessage = source.getDefaultMessage();
	if (defaultMessage != null) {
		defaultMessage = HtmlUtils.htmlEscape(defaultMessage);
	}
	if (source instanceof FieldError) {
		FieldError fieldError = (FieldError) source;
		Object value = fieldError.getRejectedValue();
		if (value instanceof String) {
			value = HtmlUtils.htmlEscape((String) value);
		}
		return (T) new FieldError(
				fieldError.getObjectName(), fieldError.getField(), value, fieldError.isBindingFailure(),
				fieldError.getCodes(), fieldError.getArguments(), defaultMessage);
	}
	else {
		return (T) new ObjectError(
				source.getObjectName(), source.getCodes(), source.getArguments(), defaultMessage);
	}
}
 
Example 2
Source File: GlobalControllerAdvice.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(code = HttpStatus.BAD_REQUEST)
public ResponseEntity<ErrorMessage> handleMethodArgumentNotValid(MethodArgumentNotValidException ex
) {
	List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
	List<ObjectError> globalErrors = ex.getBindingResult().getGlobalErrors();
	List<String> errors = new ArrayList<>(fieldErrors.size() + globalErrors.size());
	String error;
	for (FieldError fieldError : fieldErrors) {
		error = fieldError.getField() + ", " + fieldError.getDefaultMessage();
		errors.add(error);
	}
	for (ObjectError objectError : globalErrors) {
		error = objectError.getObjectName() + ", " + objectError.getDefaultMessage();
		errors.add(error);
	}
	ErrorMessage errorMessage = new ErrorMessage(errors);

	//Object result=ex.getBindingResult();//instead of above can allso pass the more detailed bindingResult
	return new ResponseEntity(errorMessage, HttpStatus.BAD_REQUEST);
}
 
Example 3
Source File: ValidatorUtils.java    From onetwo with Apache License 2.0 6 votes vote down vote up
public static List<String> asStringList(BindingResult br, boolean appendFieldname){
		if(br==null || !br.hasErrors())
			return Collections.emptyList();
		List<String> msglist = new ArrayList<String>();
		String msg = null;
		for(ObjectError error : br.getAllErrors()){
			msg = "";
			if(appendFieldname && FieldError.class.isInstance(error)){
				FieldError fe = (FieldError) error;
				FieldName info = findValidationInfo(br.getTarget().getClass(), fe.getField());
				msg = info==null?fe.getField():info.value();
//				msg = info==null?"":info.value();
			}
			msg += error.getDefaultMessage();
			msglist.add(msg);
		}
		return msglist;
	}
 
Example 4
Source File: EscapedErrors.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private <T extends ObjectError> T escapeObjectError(T source) {
	if (source == null) {
		return null;
	}
	if (source instanceof FieldError) {
		FieldError fieldError = (FieldError) source;
		Object value = fieldError.getRejectedValue();
		if (value instanceof String) {
			value = HtmlUtils.htmlEscape((String) value);
		}
		return (T) new FieldError(
				fieldError.getObjectName(), fieldError.getField(), value,
				fieldError.isBindingFailure(), fieldError.getCodes(),
				fieldError.getArguments(), HtmlUtils.htmlEscape(fieldError.getDefaultMessage()));
	}
	else {
		return (T) new ObjectError(
				source.getObjectName(), source.getCodes(), source.getArguments(),
				HtmlUtils.htmlEscape(source.getDefaultMessage()));
	}
}
 
Example 5
Source File: EscapedErrors.java    From java-technology-stack with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Nullable
private <T extends ObjectError> T escapeObjectError(@Nullable T source) {
	if (source == null) {
		return null;
	}
	String defaultMessage = source.getDefaultMessage();
	if (defaultMessage != null) {
		defaultMessage = HtmlUtils.htmlEscape(defaultMessage);
	}
	if (source instanceof FieldError) {
		FieldError fieldError = (FieldError) source;
		Object value = fieldError.getRejectedValue();
		if (value instanceof String) {
			value = HtmlUtils.htmlEscape((String) value);
		}
		return (T) new FieldError(
				fieldError.getObjectName(), fieldError.getField(), value, fieldError.isBindingFailure(),
				fieldError.getCodes(), fieldError.getArguments(), defaultMessage);
	}
	else {
		return (T) new ObjectError(
				source.getObjectName(), source.getCodes(), source.getArguments(), defaultMessage);
	}
}
 
Example 6
Source File: ParamsValidateAspect.java    From seezoon-framework-all with Apache License 2.0 6 votes vote down vote up
@Around("anyMethod() && args(..)")
public Object around(ProceedingJoinPoint point) throws Throwable {
	Object[] args = point.getArgs();
	if (null != args && args.length > 0) {
		for (Object arg : args) {
			if (arg instanceof BindingResult) {
				BindingResult br = (BindingResult) arg;
				if (br.hasErrors()) {
					FieldError fieldError = br.getFieldErrors().get(0);
					throw new ResponeException(ExceptionCode.PARAM_INVALID, "参数校验错误",
							new Object[] { fieldError.getField(), fieldError.getDefaultMessage() });
				}
			}
		}
	}
	return point.proceed();
}
 
Example 7
Source File: PetControllerExceptionHandler.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * The handleMethodArgumentNotValid method creates a response with a list of messages that contains the fields with errors
 *
 * @param exception MethodArgumentNotValidException
 * @return 400 and a list of messages with invalid fields
 */
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ApiMessageView> handleMethodArgumentNotValid(MethodArgumentNotValidException exception) {
    List<FieldError> fieldErrors = exception.getBindingResult().getFieldErrors();
    List<Object[]> messages = new ArrayList<>();

    for (FieldError fieldError : fieldErrors) {
        Object[] messageFields = new Object[3];
        messageFields[0] = fieldError.getField();
        messageFields[1] = fieldError.getRejectedValue();
        messageFields[2] = fieldError.getDefaultMessage();
        messages.add(messageFields);
    }

    List<ApiMessage> listApiMessage = messageService
        .createMessage("org.zowe.apiml.sampleservice.api.petMethodArgumentNotValid", messages)
        .stream()
        .map(Message::mapToApiMessage)
        .collect(Collectors.toList());

    return ResponseEntity
        .status(HttpStatus.BAD_REQUEST)
        .contentType(MediaType.APPLICATION_JSON_UTF8)
        .body(new ApiMessageView(listApiMessage));
}
 
Example 8
Source File: ParamValidateUtils.java    From disconf with Apache License 2.0 5 votes vote down vote up
/**
 * 从bindException中获取到参数错误类型,参数错误
 */
public static ModelAndView getParamErrors(BindException be) {

    // 构造error的映射
    Map<String, String> paramErrors = new HashMap<String, String>();
    Map<String, Object[]> paramArgusErrors = new HashMap<String, Object[]>();
    for (Object error : be.getAllErrors()) {
        if (error instanceof FieldError) {
            FieldError fe = (FieldError) error;
            String field = fe.getField();

            // 默认的message
            String message = fe.getDefaultMessage();
            try {

                contextReader.getMessage(message, fe.getArguments());

            } catch (NoSuchMessageException e) {

                // 如果有code,则从前往后遍历Code(特殊到一般),修改message为code所对应
                for (int i = fe.getCodes().length - 1; i >= 0; i--) {
                    try {
                        String code = fe.getCodes()[i];
                        String info = contextReader.getMessage(code, fe.getArguments());
                        LOG.debug(code + "\t" + info);
                        message = code;
                    } catch (NoSuchMessageException e2) {
                        LOG.debug("");
                    }
                }
            }

            // 最终的消息
            paramErrors.put(field, message);
            paramArgusErrors.put(field, fe.getArguments());
        }
    }

    return ParamValidateUtils.paramError(paramErrors, paramArgusErrors, ErrorCode.FIELD_ERROR);
}
 
Example 9
Source File: Message.java    From sdk-rest with MIT License 5 votes vote down vote up
public Message(FieldError fieldError) {
	super();
	this.detailMessage = fieldError.getDefaultMessage() + ". REJECTED VALUE = " + fieldError.getRejectedValue();
	this.propertyName = fieldError.getField();
	this.severity = "ERROR";
	this.type = "VALIDATION_ERROR";
}
 
Example 10
Source File: CustomExceptionHandler.java    From syhthems-platform with MIT License 5 votes vote down vote up
@ExceptionHandler(BindException.class)
public Object bindExceptionHandler(BindException e) {
    e.printStackTrace();
    String message = "";
    for (FieldError fieldError : e.getFieldErrors()) {
        message = "对象:" + fieldError.getObjectName() +
                " 字段:" + fieldError.getField() +
                " 错误信息:" + fieldError.getDefaultMessage() + "\n";
    }
    return ResultUtils.error(ResultEnum.ILLEGAL_CONTROLLER_ARGUMENT.getKey(), message);
}
 
Example 11
Source File: ParamValidateUtils.java    From disconf with Apache License 2.0 5 votes vote down vote up
/**
 * 从bindException中获取到参数错误类型,参数错误
 */
public static ModelAndView getParamErrors(BindException be) {

    // 构造error的映射
    Map<String, String> paramErrors = new HashMap<String, String>();
    Map<String, Object[]> paramArgusErrors = new HashMap<String, Object[]>();
    for (Object error : be.getAllErrors()) {
        if (error instanceof FieldError) {
            FieldError fe = (FieldError) error;
            String field = fe.getField();

            // 默认的message
            String message = fe.getDefaultMessage();
            try {

                contextReader.getMessage(message, fe.getArguments());

            } catch (NoSuchMessageException e) {

                // 如果有code,则从前往后遍历Code(特殊到一般),修改message为code所对应
                for (int i = fe.getCodes().length - 1; i >= 0; i--) {
                    try {
                        String code = fe.getCodes()[i];
                        String info = contextReader.getMessage(code, fe.getArguments());
                        LOG.debug(code + "\t" + info);
                        message = code;
                    } catch (NoSuchMessageException e2) {
                        LOG.debug("");
                    }
                }
            }

            // 最终的消息
            paramErrors.put(field, message);
            paramArgusErrors.put(field, fe.getArguments());
        }
    }

    return ParamValidateUtils.paramError(paramErrors, paramArgusErrors, ErrorCode.FIELD_ERROR);
}
 
Example 12
Source File: UniformHandler.java    From Milkomeda with MIT License 5 votes vote down vote up
/**
 * 处理Bean校验异常
 * @param ex            异常
 * @param bindingResult 错误绑定数据
 * @return  ResponseEntity
 */
private ResponseEntity<Object> handleValidBeanExceptionResponse(Exception ex, BindingResult bindingResult) {
    ObjectError objectError = bindingResult.getAllErrors().get(0);
    String message = objectError.getDefaultMessage();
    if (objectError.getArguments() != null && objectError.getArguments().length > 0) {
        FieldError fieldError = (FieldError) objectError;
        message = WebContext.getRequest().getRequestURI() + " [" + fieldError.getField() + "=" + fieldError.getRejectedValue() + "] " + message;
    }
    log.warn("Hydrogen uniform valid response exception with msg: {} ", message);
    return handleExceptionResponse(ex, HttpStatus.BAD_REQUEST.value(), message);
}
 
Example 13
Source File: DefaultBasicErrorConfiguring.java    From super-cloudops with Apache License 2.0 4 votes vote down vote up
/**
 * Extract meaningful errors messages.
 * 
 * @param model
 * @return
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
private String extractMeaningfulErrorsMessage(Map<String, Object> model) {
	StringBuffer errmsg = new StringBuffer();
	Object message = model.get("message");
	if (message != null) {
		errmsg.append(message);
	}

	Object errors = model.get("errors"); // @NotNull?
	if (errors != null) {
		errmsg.setLength(0); // Print only errors information
		if (errors instanceof Collection) {
			// Used to remove duplication
			List<String> fieldErrs = new ArrayList<>(8);

			Collection<Object> _errors = (Collection) errors;
			Iterator<Object> it = _errors.iterator();
			while (it.hasNext()) {
				Object err = it.next();
				if (err instanceof FieldError) {
					FieldError ferr = (FieldError) err;
					/*
					 * Remove duplicate field validation errors,
					 * e.g. @NotNull and @NotEmpty
					 */
					String fieldErr = ferr.getField();
					if (!fieldErrs.contains(fieldErr)) {
						errmsg.append("'");
						errmsg.append(fieldErr);
						errmsg.append("' ");
						errmsg.append(ferr.getDefaultMessage());
						errmsg.append(", ");
					}
					fieldErrs.add(fieldErr);
				} else {
					errmsg.append(err.toString());
					errmsg.append(", ");
				}
			}
		} else {
			errmsg.append(errors.toString());
		}
	}

	return errmsg.toString();
}
 
Example 14
Source File: OriginTrackedFieldError.java    From spring-cloud-gray with Apache License 2.0 4 votes vote down vote up
private OriginTrackedFieldError(FieldError fieldError) {
    super(fieldError.getObjectName(), fieldError.getField(),
            fieldError.getRejectedValue(), fieldError.isBindingFailure(),
            fieldError.getCodes(), fieldError.getArguments(),
            fieldError.getDefaultMessage());
}
 
Example 15
Source File: ValidationErrorResource.java    From springrestdoc with MIT License 4 votes vote down vote up
public ValidationErrorResource(FieldError fieldError) {
    this.property = fieldError.getField();
    this.message = fieldError.getDefaultMessage();
    this.invalidValue = String.valueOf(fieldError.getRejectedValue());
}
 
Example 16
Source File: ValidationErrorResource.java    From springrestdoc with MIT License 4 votes vote down vote up
public ValidationErrorResource(FieldError fieldError) {
    this.property = fieldError.getField();
    this.message = fieldError.getDefaultMessage();
    this.invalidValue = String.valueOf(fieldError.getRejectedValue());
}
 
Example 17
Source File: FormErrorRepresentation.java    From abixen-platform with GNU Lesser General Public License v2.1 4 votes vote down vote up
public FormErrorRepresentation(FieldError fieldError) {
    this.field = fieldError.getField();
    this.code = fieldError.getCode();
    this.message = fieldError.getDefaultMessage();
    this.rejectedValue = fieldError.getRejectedValue();
}
 
Example 18
Source File: BindingResultSerializer.java    From springlets with Apache License 2.0 4 votes vote down vote up
/**
 * Iterate over list items errors and load it on allErrorsMessages map.
 * <p/>
 * Delegates on {@link #loadObjectError(FieldError, String, Map)}
 * 
 * @param fieldErrors
 * @param allErrorsMessages
 */
@SuppressWarnings("unchecked")
private void loadListErrors(List<FieldError> fieldErrors, Map<String, Object> allErrorsMessages) {

  // Get prefix to unwrapping list:
  // "list[0].employedSince"
  String fieldNamePath = fieldErrors.get(0).getField();
  String prefix = "";

  if (fieldNamePath != null && fieldNamePath.contains("[")) {
    // "list"
    prefix = substringBefore(fieldNamePath, "[");
  }

  String index = "";
  Map<String, Object> currentErrors;

  // Iterate over errors
  for (FieldError error : fieldErrors) {

    fieldNamePath = error.getField();

    if (fieldNamePath != null && fieldNamePath.contains("]")) {

      // get property path without list prefix
      // "[0].employedSince"
      fieldNamePath = substringAfter(error.getField(), prefix);

      // Get item's index:
      // "[0].employedSince"
      index = substringBefore(substringAfter(fieldNamePath, "["), "]");

      // Remove index definition from field path
      // "employedSince"
      fieldNamePath = substringAfter(fieldNamePath, ".");
    }

    // Check if this item already has errors registered
    currentErrors = (Map<String, Object>) allErrorsMessages.get(index);
    if (currentErrors == null) {
      // No errors registered: create map to contain this error
      currentErrors = new HashMap<String, Object>();
      allErrorsMessages.put(index, currentErrors);
    }

    // Load error on item's map
    loadObjectError(error, fieldNamePath, currentErrors);
  }
}
 
Example 19
Source File: ValidationResult.java    From alf.io with GNU General Public License v3.0 4 votes vote down vote up
public static ErrorDescriptor fromFieldError(FieldError fieldError) {
    return new ErrorDescriptor(fieldError.getField(), "", fieldError.getCode(), fieldError.getArguments());
}
 
Example 20
Source File: EscapedErrors.java    From spring4-understanding with Apache License 2.0 votes vote down vote up
@SuppressWarnings("unchecked")
private <T extends ObjectError> T escapeObjectError(T source) {
	if (source == null) {
		return null;
	}
	if (source instanceof FieldError) {
		FieldError fieldError = (FieldError) source;
		Object value = fieldError.getRejectedValue();
		if (value instanceof String) {
			value = HtmlUtils.htmlEscape((String) value);
		}
		return (T) new FieldError(
				fieldError.getObjectName(), fieldError.getField(), value,
				fieldError.isBindingFailure(), fieldError.getCodes(),
				fieldError.getArguments(), HtmlUtils.htmlEscape(fieldError.getDefaultMessage()));
	}
	else {
		return (T) new ObjectError(
				source.getObjectName(), source.getCodes(), source.getArguments(),
				HtmlUtils.htmlEscape(source.getDefaultMessage()));
	}
}