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

The following examples show how to use org.springframework.validation.FieldError#getDefaultMessage() . 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: 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 2
Source File: BaseController.java    From disconf with Apache License 2.0 6 votes vote down vote up
/**
 * 错误:参数错误
 *
 * @param bindingResult
 *
 * @return
 */
protected JsonObjectBase buildFieldError(BindingResult bindingResult, ErrorCode errorCode) {

    Map<String, String> errors = new HashMap<String, String>();
    for (Object object : bindingResult.getAllErrors()) {
        if (object instanceof FieldError) {
            FieldError fieldError = (FieldError) object;
            String message = fieldError.getDefaultMessage();
            errors.put(fieldError.getField(), message);
        }
    }

    if (errorCode == null) {
        return JsonObjectUtils.buildFieldError(errors, ErrorCode.FIELD_ERROR);
    }
    return JsonObjectUtils.buildFieldError(errors, errorCode);
}
 
Example 3
Source File: ValidationBindingResult.java    From onetwo with Apache License 2.0 6 votes vote down vote up
public String getFieldErrorMessage(FieldError fe, boolean readFieldMeta){
		if(fe==null){
//			throw new JFishException("can not find this field named : " + fieldName);
			return "";
		}

		String fmsg = null;
		if(readFieldMeta){
			JFishProperty jp = JFishPropertyFactory.create(getTarget().getClass(), fe.getField(), true);
			if(jp==null)
				jp = JFishPropertyFactory.create(getTarget().getClass(), fe.getField(), false);
			FieldName jfm = jp.getAnnotation(FieldName.class);
			if(jfm==null){
				fmsg = LangUtils.append(fe.getField(), fe.getDefaultMessage());
			}else{
				fmsg = LangUtils.append(jfm.value(), fe.getDefaultMessage());
			}
		}else{
			fmsg = fe.getDefaultMessage();
		}
		return fmsg;
	}
 
Example 4
Source File: BaseController.java    From disconf with Apache License 2.0 6 votes vote down vote up
/**
 * 错误:参数错误
 *
 * @param bindingResult
 *
 * @return
 */
protected JsonObjectBase buildFieldError(BindingResult bindingResult, ErrorCode errorCode) {

    Map<String, String> errors = new HashMap<String, String>();
    for (Object object : bindingResult.getAllErrors()) {
        if (object instanceof FieldError) {
            FieldError fieldError = (FieldError) object;
            String message = fieldError.getDefaultMessage();
            errors.put(fieldError.getField(), message);
        }
    }

    if (errorCode == null) {
        return JsonObjectUtils.buildFieldError(errors, ErrorCode.FIELD_ERROR);
    }
    return JsonObjectUtils.buildFieldError(errors, errorCode);
}
 
Example 5
Source File: ResponseEntityExceptionHandlerEx.java    From JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
                                                              HttpHeaders headers,
                                                              HttpStatus status,
                                                              WebRequest request) {
    ValidationErrorDto dto = new ValidationErrorDto();
    for (FieldError fieldError : ex.getBindingResult().getFieldErrors()) {
        String localizedErrorMessage = fieldError.getDefaultMessage();
        String[] fieldErrorCodes = fieldError.getCodes();
        if (fieldErrorCodes != null) {
            localizedErrorMessage = fieldErrorCodes[0];
        }
        dto.addFieldError(fieldError.getField(), localizedErrorMessage);
    }
    return ResponseEntity.badRequest().body(dto);
}
 
Example 6
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 7
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 8
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 9
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 10
Source File: ThrowableUtils.java    From plumemo with Apache License 2.0 5 votes vote down vote up
/**
 * 校验参数正确,拼装字段名和值到错误信息
 * @param result
 */
public static void checkParamArgument(BindingResult result) {
    if (result != null && result.hasErrors()) {
        StringBuilder sb = new StringBuilder();
        List<FieldError> errors = result.getFieldErrors();
        if(CollectionUtil.isNotEmpty(errors)){
            FieldError error = errors.get(0);
            String rejectedValue = Objects.toString(error.getRejectedValue(), "");
            String defMsg = error.getDefaultMessage();
            // 排除类上面的注解提示
            if(rejectedValue.contains(Constants.DELIMITER_TO)){
                // 自己去确定错误字段
                sb.append(defMsg);
            }else{
                if(Constants.DELIMITER_COLON.contains(defMsg)){
                    sb.append(error.getField()).append(" ").append(defMsg);
                }else{
                    sb.append(error.getField()).append(" ").append(defMsg).append(":").append(rejectedValue);
                }
            }
        } else {
            String msg = result.getAllErrors().get(0).getDefaultMessage();
            sb.append(msg);
        }
        throw new ApiInvalidParamException(sb.toString());
    }
}
 
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: RestExceptionHandler.java    From plumemo with Apache License 2.0 5 votes vote down vote up
/**
 * validation 异常处理
 *
 * @param request 请求体
 * @param e       MethodArgumentNotValidException
 * @return HttpResult
 */
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
public Result onMethodArgumentNotValidException(HttpServletRequest request,
                                                MethodArgumentNotValidException e) {
    BindingResult result = e.getBindingResult();
    if (result != null && result.hasErrors()) {
        StringBuilder sb = new StringBuilder();
        List<FieldError> errors = result.getFieldErrors();
        if(CollectionUtil.isNotEmpty(errors)){
            FieldError error = errors.get(0);
            String rejectedValue = Objects.toString(error.getRejectedValue(), "");
            String defMsg = error.getDefaultMessage();
            // 排除类上面的注解提示
            if(rejectedValue.contains(Constants.DELIMITER_TO)){
                // 自己去确定错误字段
                sb.append(defMsg);
            }else{
                if(Constants.DELIMITER_COLON.contains(defMsg)){
                    sb.append(error.getField()).append(" ").append(defMsg);
                }else{
                    sb.append(error.getField()).append(" ").append(defMsg).append(":").append(rejectedValue);
                }
            }
        } else {
            String msg = result.getAllErrors().get(0).getDefaultMessage();
            sb.append(msg);
        }

        return Result.createWithErrorMessage(sb.toString(), ErrorEnum.PARAM_ERROR.getCode());
    }

    return null;
}
 
Example 13
Source File: ThrowableUtils.java    From mogu_blog_v2 with Apache License 2.0 5 votes vote down vote up
/**
 * 校验参数正确,拼装字段名和值到错误信息
 *
 * @param result
 */
public static void checkParamArgument(BindingResult result) {
    if (result != null && result.hasErrors()) {
        StringBuilder sb = new StringBuilder();
        List<FieldError> errors = result.getFieldErrors();
        if (CollectionUtil.isNotEmpty(errors)) {
            FieldError error = errors.get(0);
            String rejectedValue = Objects.toString(error.getRejectedValue(), "");
            String defMsg = error.getDefaultMessage();
            // 排除类上面的注解提示
            if (rejectedValue.contains(Constants.DELIMITER_TO)) {
                // 自己去确定错误字段
                sb.append(defMsg);
            } else {
                if (Constants.DELIMITER_COLON.contains(defMsg)) {
                    sb.append(error.getField()).append(" ").append(defMsg);
                } else {
                    sb.append(error.getField()).append(" ").append(defMsg);
                    // sb.append(error.getField()).append(" ").append(defMsg).append(":").append(rejectedValue);
                }
            }
        } else {
            String msg = result.getAllErrors().get(0).getDefaultMessage();
            sb.append(msg);
        }
        throw new ApiInvalidParamException(sb.toString());
    }

}
 
Example 14
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 15
Source File: GlobalExceptionHandler.java    From EosProxyServer with GNU Lesser General Public License v3.0 4 votes vote down vote up
@ExceptionHandler
@ResponseStatus
public ResponseEntity<MessageResult> hadleServerException(Exception exception) {

    //默认打印错误,并且返回server error
    exception.printStackTrace();
    HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
    Integer code = ErrorCodeEnumChain.unknown_error_exception.getMsg_id();
    String msg = ErrorCodeEnumChain.getMsgById(code);

    //不支持的method
    if(exception instanceof HttpRequestMethodNotSupportedException) {
        httpStatus = HttpStatus.NOT_FOUND;
        code = ErrorCodeEnumChain.not_supported_exception.getMsg_id();
        msg = exception.getMessage();
    }
    //没有handler
    else if (exception instanceof NoHandlerFoundException) {
        httpStatus = HttpStatus.BAD_REQUEST;
        code = ErrorCodeEnumChain.not_supported_exception.getMsg_id();
        msg = exception.getMessage();
    }
    //缺失parameter
    else if (exception instanceof MissingServletRequestParameterException) {
        httpStatus = HttpStatus.BAD_REQUEST;
        code = ErrorCodeEnumChain.not_supported_exception.getMsg_id();
        msg = exception.getMessage();
    }
    else if (exception instanceof RedisConnectionException) {
        httpStatus = HttpStatus.BAD_REQUEST;
        code = ErrorCodeEnumChain.redis_connection_exception.getMsg_id();
        msg = exception.getMessage();
    }
    else if(exception instanceof MethodArgumentTypeMismatchException){
        httpStatus = HttpStatus.BAD_REQUEST;
        code = ErrorCodeEnumChain.request_format_exception.getMsg_id();
        msg = exception.getMessage();
    }
    else if(exception instanceof MethodArgumentNotValidException){
        httpStatus = HttpStatus.BAD_REQUEST;
        code = ErrorCodeEnumChain.request_format_exception.getMsg_id();
        BindingResult bindingResult = ((MethodArgumentNotValidException) exception).getBindingResult();
        msg = "parameter validate error:";
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            msg += fieldError.getDefaultMessage() + ", ";
        }
    }
    log.warn("X--->{code:" + code + ",msg:" + msg + ",what:" + exception.getMessage());
    return new ResponseEntity(new MessageResult(msg, code, exception.getMessage()), httpStatus);
}
 
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: 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 18
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 19
Source File: BaseBindingResultAdviceTrait.java    From problem-spring-web with MIT License 4 votes vote down vote up
default Violation createViolation(final FieldError error) {
    final String fieldName = formatFieldName(error.getField());
    return new Violation(fieldName, error.getDefaultMessage());
}
 
Example 20
Source File: BaseBindingResultAdviceTrait.java    From problem-spring-web with MIT License 4 votes vote down vote up
default Violation createViolation(final FieldError error) {
    final String fieldName = formatFieldName(error.getField());
    return new Violation(fieldName, error.getDefaultMessage());
}