Here are the examples of the java api org.springframework.validation.ObjectError taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
121 Examples
19
View Source File : BindValidationFailureAnalyzer.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
private Failurereplacedysis replacedyzeBindValidationException(ExceptionDetails details) {
StringBuilder description = new StringBuilder(String.format("Binding to target %s failed:%n", details.getTarget()));
for (ObjectError error : details.getErrors()) {
if (error instanceof FieldError) {
appendFieldError(description, (FieldError) error);
}
description.append(String.format("%n Reason: %s%n", error.getDefaultMessage()));
}
return getFailurereplacedysis(description, details.getCause());
}
19
View Source File : BindStatus.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* Extract the error messages from the ObjectError list.
*/
private String[] initErrorMessages() throws NoSuchMessageException {
if (this.errorMessages == null) {
if (this.objectErrors != null) {
this.errorMessages = new String[this.objectErrors.size()];
for (int i = 0; i < this.objectErrors.size(); i++) {
ObjectError error = this.objectErrors.get(i);
this.errorMessages[i] = this.requestContext.getMessage(error, this.htmlEscape);
}
} else {
this.errorMessages = new String[0];
}
}
return this.errorMessages;
}
19
View Source File : WebExchangeBindException.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Override
public void addError(ObjectError error) {
this.bindingResult.addError(error);
}
19
View Source File : MethodArgumentNotValidException.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Override
public String getMessage() {
StringBuilder sb = new StringBuilder("Validation failed for argument [").append(this.parameter.getParameterIndex()).append("] in ").append(this.parameter.getExecutable().toGenericString());
if (this.bindingResult.getErrorCount() > 1) {
sb.append(" with ").append(this.bindingResult.getErrorCount()).append(" errors");
}
sb.append(": ");
for (ObjectError error : this.bindingResult.getAllErrors()) {
sb.append("[").append(error).append("] ");
}
return sb.toString();
}
19
View Source File : MethodArgumentNotValidException.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
private static String getValidationErrorMessage(BindingResult bindingResult) {
StringBuilder sb = new StringBuilder();
sb.append(bindingResult.getErrorCount()).append(" error(s): ");
for (ObjectError error : bindingResult.getAllErrors()) {
sb.append("[").append(error).append("] ");
}
return sb.toString();
}
19
View Source File : ApiError.java
License : MIT License
Project Creator : SystangoTechnologies
License : MIT License
Project Creator : SystangoTechnologies
private void addValidationError(ObjectError objectError) {
this.addValidationError(objectError.getObjectName(), objectError.getDefaultMessage());
}
19
View Source File : BeanValidationException.java
License : Mozilla Public License 2.0
Project Creator : SafeExamBrowser
License : Mozilla Public License 2.0
Project Creator : SafeExamBrowser
@Override
public String getMessage() {
final StringBuilder sb = new StringBuilder("Validation failed for ");
if (this.bindingResult.getErrorCount() > 1) {
sb.append(" with ").append(this.bindingResult.getErrorCount()).append(" errors");
}
sb.append(": ");
for (final ObjectError error : this.bindingResult.getAllErrors()) {
sb.append("[").append(error).append("] ");
}
return sb.toString();
}
19
View Source File : ResultMessageVO.java
License : Apache License 2.0
Project Creator : pleuvoir
License : Apache License 2.0
Project Creator : pleuvoir
public static <T> ResultMessageVO<T> error(ObjectError message) {
ResultMessageVO<T> msg = new ResultMessageVO<>();
msg.setStatus(ERROR);
msg.setMessage(message.getDefaultMessage());
return msg;
}
19
View Source File : AlertMessage.java
License : Apache License 2.0
Project Creator : pleuvoir
License : Apache License 2.0
Project Creator : pleuvoir
/**
* 创建参数校验失败消息
* @param message 参数错误信息
* @return
*/
public static AlertMessage error(ObjectError message) {
return new AlertMessage(ERROR, message);
}
19
View Source File : Jsr303Controller.java
License : GNU General Public License v3.0
Project Creator : mytianya
License : GNU General Public License v3.0
Project Creator : mytianya
public static void check(BindingResult result) {
StringBuffer sb = new StringBuffer();
if (result.hasErrors()) {
for (ObjectError error : result.getAllErrors()) {
sb.append(error.getDefaultMessage());
}
ExUtil.throwBusException(sb.toString());
}
}
19
View Source File : BindStatus.java
License : Apache License 2.0
Project Creator : langtianya
License : Apache License 2.0
Project Creator : langtianya
/**
* Extract the error codes from the ObjectError list.
*/
private void initErrorCodes() {
this.errorCodes = new String[this.objectErrors.size()];
for (int i = 0; i < this.objectErrors.size(); i++) {
ObjectError error = this.objectErrors.get(i);
this.errorCodes[i] = error.getCode();
}
}
19
View Source File : BindStatus.java
License : Apache License 2.0
Project Creator : langtianya
License : Apache License 2.0
Project Creator : langtianya
/**
* Extract the error messages from the ObjectError list.
*/
private void initErrorMessages() throws NoSuchMessageException {
if (this.errorMessages == null) {
this.errorMessages = new String[this.objectErrors.size()];
for (int i = 0; i < this.objectErrors.size(); i++) {
ObjectError error = this.objectErrors.get(i);
this.errorMessages[i] = this.requestContext.getMessage(error, this.htmlEscape);
}
}
}
19
View Source File : MethodArgumentNotValidException.java
License : Apache License 2.0
Project Creator : langtianya
License : Apache License 2.0
Project Creator : langtianya
@Override
public String getMessage() {
StringBuilder sb = new StringBuilder("Validation failed for argument at index ").append(this.parameter.getParameterIndex()).append(" in method: ").append(this.parameter.getMethod().toGenericString()).append(", with ").append(this.bindingResult.getErrorCount()).append(" error(s): ");
for (ObjectError error : this.bindingResult.getAllErrors()) {
sb.append("[").append(error).append("] ");
}
return sb.toString();
}
19
View Source File : MethodArgumentNotValidException.java
License : Apache License 2.0
Project Creator : langtianya
License : Apache License 2.0
Project Creator : langtianya
private static String getValidationErrorMessage(BindingResult bindingResult) {
if (bindingResult != null) {
StringBuilder sb = new StringBuilder();
sb.append(", with ").append(bindingResult.getErrorCount()).append(" error(s): ");
for (ObjectError error : bindingResult.getAllErrors()) {
sb.append("[").append(error).append("] ");
}
return sb.toString();
} else {
return "";
}
}
19
View Source File : BaseController.java
License : Apache License 2.0
Project Creator : jiangmin168168
License : Apache License 2.0
Project Creator : jiangmin168168
private String getAllParametersInValidMsg(List<ObjectError> allErrors) {
if (null == allErrors) {
return "";
}
StringBuffer stringBuffer = new StringBuffer();
for (ObjectError error : allErrors) {
if (null != error) {
stringBuffer.append(error.getDefaultMessage() + ",");
}
}
return stringBuffer.toString();
}
19
View Source File : ValidationMessages.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
//
// The arguments provided by the Binding Errors here include as their first argument a version of all the error message
// information itself stored as a MessageSourceResolvable. We don't want to be sending this across to the web layer
// as it's useless information. We also can't really filter it out entirely because the resource bundle entries in the
// web layer expect the useful arguments from a Binding Error to be in a particular position in order to work (for instance,
//
// "validation.standard.lastname.length.min=Your last name should have at least {2} characters"
//
// expects the actual useful argument to be in array index 2, and this is a resource bundle argument that potentially
// could be got from either the data layer or the web layer, so it's best that we retain the original order of arguments
// in the data layer to make these resource bundle entries reusable. Therefore, we're best off just replacing the
// MessageSourceResolvable argument with a blank entry.
//
private List<Object> getArgumentsFromBindingError(ObjectError e) {
Object[] originalArguments = e.getArguments();
if (originalArguments == null || originalArguments.length == 0) {
return emptyList();
}
return simpleMap(asList(originalArguments), arg -> getValidMessageArgument(arg).orElse(""));
}
19
View Source File : CircusTrainHelpTest.java
License : Apache License 2.0
Project Creator : HotelsDotCom
License : Apache License 2.0
Project Creator : HotelsDotCom
@Test
public void convertErrorToTabPrependedString() {
ObjectError error = new ObjectError("object.name", "this an error message");
String errorMessage = CircusTrainHelp.OBJECT_ERROR_TO_TABBED_MESSAGE.apply(error);
replacedertThat(errorMessage, is("\tthis an error message"));
}
19
View Source File : StackValidationExceptionHandler.java
License : Mozilla Public License 2.0
Project Creator : gaia-app
License : Mozilla Public License 2.0
Project Creator : gaia-app
private String getMessage(ObjectError error) {
if (error instanceof FieldError) {
var fieldError = ((FieldError) error);
return fieldError.getField() + " " + fieldError.getDefaultMessage();
}
return error.getDefaultMessage();
}
19
View Source File : SpringValidationWebErrorHandler.java
License : Apache License 2.0
Project Creator : alimate
License : Apache License 2.0
Project Creator : alimate
/**
* Extracting the error code from the given {@link ObjectError}. Also, before returning
* the error code, would strip the curly braces form the error code, if any (We have our own
* message interpolation!).
*
* @param error Encapsulates the error details.
* @return The error code.
*/
private String errorCode(ObjectError error) {
String code = null;
try {
code = ConstraintViolations.getErrorCode(error.unwrap(ConstraintViolation.clreplaced));
} catch (Exception ignored) {
}
if (code == null) {
try {
code = TypeMismatchWebErrorHandler.getErrorCode(error.unwrap(TypeMismatchException.clreplaced));
} catch (Exception ignored) {
}
}
if (code == null)
code = BINDING_FAILURE;
return code.replace("{", "").replace("}", "");
}
19
View Source File : SpringValidationWebErrorHandler.java
License : Apache License 2.0
Project Creator : alimate
License : Apache License 2.0
Project Creator : alimate
/**
* Extracts the arguments from the validation meta data and exposes them to the outside
* world. First try to unwrap {@link ConstraintViolation} and if successful, use
* {@link ConstraintViolations#getArguments(ConstraintViolation)}.
*
* @param error Encapsulates the error details.
* @return Collection of all arguments for the given {@code error} details.
*/
private List<Argument> arguments(ObjectError error) {
try {
ConstraintViolation<?> violation = error.unwrap(ConstraintViolation.clreplaced);
return ConstraintViolations.getArguments(violation);
} catch (Exception ignored) {
}
try {
return TypeMismatchWebErrorHandler.getArguments(error.unwrap(TypeMismatchException.clreplaced));
} catch (Exception ignored) {
}
return emptyList();
}
19
View Source File : TagController.java
License : GNU General Public License v3.0
Project Creator : Alension
License : GNU General Public License v3.0
Project Creator : Alension
/**
* 新增/修改标签
*
* @param tag tag
*
* @return JsonResult
*/
@PostMapping(value = "/save")
@ResponseBody
public JsonResult saveTag(@Valid Tag tag, BindingResult result) {
if (result.hasErrors()) {
for (ObjectError error : result.getAllErrors()) {
return new JsonResult(ResultCodeEnum.FAIL.getCode(), error.getDefaultMessage());
}
}
final Tag tempTag = tagService.findByTagUrl(tag.getTagUrl());
if (null != tag.getTagId()) {
if (null != tempTag && !tag.getTagId().equals(tempTag.getTagId())) {
return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.common.url-is-exists"));
}
} else {
if (null != tempTag) {
return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.common.url-is-exists"));
}
}
tag = tagService.save(tag);
if (null == tag) {
return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.common.save-failed"));
}
return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.common.save-success"));
}
19
View Source File : PageController.java
License : GNU General Public License v3.0
Project Creator : Alension
License : GNU General Public License v3.0
Project Creator : Alension
/**
* 处理添加/修改友链的请求并渲染页面
*
* @param link Link实体
*
* @return JsonResult
*/
@PostMapping(value = "/links/save")
@ResponseBody
public JsonResult saveLink(@Valid Link link, BindingResult result) {
if (result.hasErrors()) {
for (ObjectError error : result.getAllErrors()) {
return new JsonResult(ResultCodeEnum.FAIL.getCode(), error.getDefaultMessage());
}
}
link = linkService.save(link);
if (null == link) {
return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.common.save-failed"));
}
return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.common.save-success"));
}
18
View Source File : ValidationErrors.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
private ObjectError convertError(ConfigurationPropertyName name, Set<ConfigurationProperty> boundProperties, ObjectError error) {
if (error instanceof FieldError) {
return convertFieldError(name, boundProperties, (FieldError) error);
}
return error;
}
18
View Source File : ObjectErrorSerializer.java
License : Apache License 2.0
Project Creator : xiangxik
License : Apache License 2.0
Project Creator : xiangxik
@Override
public void serialize(ObjectError value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
if (value == null) {
gen.writeNull();
return;
}
gen.writeStartObject();
gen.writeStringField("objectName", value.getObjectName());
gen.writeStringField("code", value.getCode());
gen.writeStringField("defaultMessage", value.getDefaultMessage());
if (value instanceof FieldError) {
gen.writeStringField("field", ((FieldError) value).getField());
gen.writeObjectField("rejectedValue", ((FieldError) value).getRejectedValue());
}
gen.writeEndObject();
}
18
View Source File : GlobalExceptionHandler.java
License : GNU Affero General Public License v3.0
Project Creator : xggz
License : GNU Affero General Public License v3.0
Project Creator : xggz
/**
* 参数校验异常处理
*
* @param e
* @return
*/
@ExceptionHandler(MethodArgumentNotValidException.clreplaced)
public Res handlerMethodArgumentNotValidException(MethodArgumentNotValidException e) {
StringBuilder message = new StringBuilder();
BindingResult bindingResult = e.getBindingResult();
for (ObjectError error : bindingResult.getAllErrors()) {
if (message.length() > 0) {
message.append("、");
}
message.append(error.getDefaultMessage());
}
return Res.failed(message.toString());
}
18
View Source File : BindStatus.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* Extract the error codes from the ObjectError list.
*/
private static String[] initErrorCodes(List<? extends ObjectError> objectErrors) {
String[] errorCodes = new String[objectErrors.size()];
for (int i = 0; i < objectErrors.size(); i++) {
ObjectError error = objectErrors.get(i);
errorCodes[i] = error.getCode();
}
return errorCodes;
}
18
View Source File : GlobalControllerAdvice.java
License : Apache License 2.0
Project Creator : springdoc
License : Apache License 2.0
Project Creator : springdoc
@ExceptionHandler(MethodArgumentNotValidException.clreplaced)
@ResponseStatus(code = HttpStatus.BAD_REQUEST)
public ResponseEnreplacedy<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 preplaced the more detailed bindingResult
return new ResponseEnreplacedy(errorMessage, HttpStatus.BAD_REQUEST);
}
18
View Source File : ExceptionControllerAdvice.java
License : Apache License 2.0
Project Creator : RudeCrab
License : Apache License 2.0
Project Creator : RudeCrab
@ExceptionHandler(MethodArgumentNotValidException.clreplaced)
public ResultVO<String> MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
// 从异常对象中拿到ObjectError对象
ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
// 然后提取错误提示信息进行返回
return new ResultVO<>(ResultCode.VALIDATE_FAILED, objectError.getDefaultMessage());
}
18
View Source File : ExceptionControllerAdvice.java
License : Apache License 2.0
Project Creator : RudeCrab
License : Apache License 2.0
Project Creator : RudeCrab
@ExceptionHandler(MethodArgumentNotValidException.clreplaced)
public ResultVO<String> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
// 从异常对象中拿到ObjectError对象
ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
// 然后提取错误提示信息进行返回
return new ResultVO<>(ResultCode.VALIDATE_FAILED, objectError.getDefaultMessage());
}
18
View Source File : AlertTag.java
License : Apache License 2.0
Project Creator : pleuvoir
License : Apache License 2.0
Project Creator : pleuvoir
/**
* 生成错误信息标签
*/
private String alertErrorTag(AlertMessage msg) {
String alertMsg = StringUtils.EMPTY;
if (msg.getMessage() instanceof String) {
alertMsg = (String) msg.getMessage();
}
if (msg.getMessage() instanceof ObjectError) {
ObjectError err = (ObjectError) msg.getMessage();
alertMsg = err.getDefaultMessage();
}
if (StringUtils.isBlank(alertMsg)) {
logger.warn("未传入有效的消息,status:{},message:{}", msg.getStatus(), msg.getMessage());
return StringUtils.EMPTY;
}
return createTag("danger", alertMsg);
}
18
View Source File : ConventionBasedSpringValidationErrorToApiErrorHandlerListener.java
License : Apache License 2.0
Project Creator : Nike-Inc
License : Apache License 2.0
Project Creator : Nike-Inc
/**
* Helper method for translating the given springErrors set into a set of {@link ApiError} objects by calling {@link
* #convertSpringErrorToApiError(ObjectError)} on each one.
*/
protected SortedApiErrorSet convertSpringErrorsToApiErrors(List<ObjectError> springErrors) {
SortedApiErrorSet apiErrors = new SortedApiErrorSet();
for (ObjectError springError : springErrors) {
apiErrors.add(convertSpringErrorToApiError(springError));
}
return apiErrors;
}
18
View Source File : ExceptionsControllerAdvice.java
License : GNU General Public License v3.0
Project Creator : MoeraOrg
License : GNU General Public License v3.0
Project Creator : MoeraOrg
@ExceptionHandler
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Result validation(MethodArgumentNotValidException e) {
ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
String errorCode = objectError.getCodes() != null && objectError.getCodes().length > 0 ? objectError.getCodes()[0] : "";
String message = messageSource.getMessage(objectError, Locale.getDefault());
return new Result(errorCode.toLowerCase(), message);
}
18
View Source File : ExceptionControllerAdvice.java
License : GNU General Public License v3.0
Project Creator : luoye663
License : GNU General Public License v3.0
Project Creator : luoye663
/**
* 参数校验
* @param e:
* @Author: 落叶随风
* @Date: 2020/9/21 11:28
* @Return: * @return: io.qyi.push.config.bean.ResultVO<java.lang.String>
*/
@ExceptionHandler(BindException.clreplaced)
public ResultVO<String> BindException(BindException e) {
ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
return new ResultVO<>(ResultCode.VALIDATE_FAILED, objectError.getDefaultMessage());
}
18
View Source File : ExceptionControllerAdvice.java
License : GNU General Public License v3.0
Project Creator : luoye663
License : GNU General Public License v3.0
Project Creator : luoye663
@ExceptionHandler(MethodArgumentNotValidException.clreplaced)
public ResultVO<String> MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
return new ResultVO<>(ResultCode.VALIDATE_FAILED, objectError.getDefaultMessage());
}
18
View Source File : LoginController.java
License : GNU General Public License v3.0
Project Creator : lovelifeming
License : GNU General Public License v3.0
Project Creator : lovelifeming
/**
* @Author: zengsm.
* @Description:
* @Date:Created in 2019/2/25 17:19.
* @Modified By:
*/
@RestController
@RequestMapping("/login/")
public clreplaced LoginController {
private ObjectError error;
@RequestMapping("index.html")
public ModelAndView index() {
return new ModelAndView("login");
}
@PostMapping("login.jsp")
public RespResult login(@Valid LoginVO loginVO, BindingResult bindingResult, Model mode) {
if (bindingResult.hasErrors()) {
for (ObjectError error : bindingResult.getAllErrors()) {
return RespResult.failure(error.getDefaultMessage());
}
}
return RespResult.success("验证成功");
}
}
18
View Source File : LoginController.java
License : GNU General Public License v3.0
Project Creator : lovelifeming
License : GNU General Public License v3.0
Project Creator : lovelifeming
@PostMapping("login.jsp")
public RespResult login(@Valid LoginVO loginVO, BindingResult bindingResult, Model mode) {
if (bindingResult.hasErrors()) {
for (ObjectError error : bindingResult.getAllErrors()) {
return RespResult.failure(error.getDefaultMessage());
}
}
return RespResult.success("验证成功");
}
18
View Source File : AuthControllerAdvice.java
License : Apache License 2.0
Project Creator : isopropylcyanide
License : Apache License 2.0
Project Creator : isopropylcyanide
/**
* Resolve localized error message. Utility method to generate a localized error
* message
*
* @param objectError the field error
* @return the string
*/
private String resolveLocalizedErrorMessage(ObjectError objectError) {
Locale currentLocale = LocaleContextHolder.getLocale();
String localizedErrorMessage = messageSource.getMessage(objectError, currentLocale);
logger.info(localizedErrorMessage);
return localizedErrorMessage;
}
18
View Source File : ValidationMessages.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
// The Binding Errors in the API contain error keys which can be looked up in the web layer (or used in another client
// of this API) to produce plain english messages, but it is not the responsibility of the API to produce plain
// english messages. Therefore, the "defaultMessage" value in these errors is actually the key that is needed by
// the web layer to produce the appropriate messages e.g. "validation.standard.email.length.max".
//
// The format we receive these in at this point is "{validation.standard.email.length.max}", so we need to ensure
// that the curly brackets are stripped off before returning to the web layer
private String getErrorKeyFromBindingError(ObjectError e) {
String messageKey = e.getDefaultMessage();
if (messageKey == null) {
return null;
}
return stripCurlyBrackets(messageKey);
}
18
View Source File : MenuController.java
License : GNU General Public License v3.0
Project Creator : Alension
License : GNU General Public License v3.0
Project Creator : Alension
/**
* 新增/修改菜单
*
* @param menu menu
*
* @return 重定向到/admin/menus
*/
@PostMapping(value = "/save")
@ResponseBody
public JsonResult saveMenu(@Valid Menu menu, BindingResult result) {
if (result.hasErrors()) {
for (ObjectError error : result.getAllErrors()) {
return new JsonResult(ResultCodeEnum.FAIL.getCode(), error.getDefaultMessage());
}
}
menu = menuService.save(menu);
if (null != menu) {
return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), "菜单保存成功!");
} else {
return new JsonResult(ResultCodeEnum.FAIL.getCode(), "菜单保存成功!");
}
}
17
View Source File : WebExceptionHandler.java
License : MIT License
Project Creator : zhaojun1998
License : MIT License
Project Creator : zhaojun1998
@ExceptionHandler
public String methodArgumentNotValid(BindException e) {
if (log.isDebugEnabled()) {
log.debug("参数校验失败", e);
}
List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
StringBuilder errorMessage = new StringBuilder();
for (int i = 0; i < allErrors.size(); i++) {
ObjectError error = allErrors.get(i);
errorMessage.append(error.getDefaultMessage());
if (i != allErrors.size() - 1) {
errorMessage.append(",");
}
}
return generateErrorInfo(ResultBean.FAIL, errorMessage.toString());
}
17
View Source File : UniformHandler.java
License : MIT License
Project Creator : yizzuide
License : MIT License
Project Creator : yizzuide
/**
* 处理Bean校验异常
* @param ex 异常
* @param bindingResult 错误绑定数据
* @return ResponseEnreplacedy
*/
private ResponseEnreplacedy<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);
}
17
View Source File : ApiResponse.java
License : Apache License 2.0
Project Creator : xuminwlt
License : Apache License 2.0
Project Creator : xuminwlt
/**
* 参数绑定错误响应
*
* @param exception 异常
* @return 响应
*/
public static ApiResponse createRestResponse(BindException exception, HttpServletRequest request) {
Builder builder = newBuilder();
if (null != exception && exception.hasErrors()) {
StringBuilder error = new StringBuilder("");
for (ObjectError objectError : exception.getAllErrors()) {
error.append(objectError.getDefaultMessage() + ";");
}
log.error(error.toString());
builder.status(BaseApiStatus.SYST_SERVICE_UNAVAILABLE);
builder.error(getMessage(String.valueOf(builder.getThis().status), request));
}
return builder.data(null).build();
}
17
View Source File : BaseController.java
License : Apache License 2.0
Project Creator : WeBankFinTech
License : Apache License 2.0
Project Creator : WeBankFinTech
/**
* Parameters check message format.
*
* @param bindingResult checkResult
* @return
*/
private String getParamValidFaildMessage(BindingResult bindingResult) {
List<ObjectError> errorList = bindingResult.getAllErrors();
log.info("errorList:{}", JsonUtils.toJSONString(errorList));
if (errorList == null) {
log.warn("onWarning:errorList is empty!");
return null;
}
ObjectError objectError = errorList.get(0);
if (objectError == null) {
log.warn("onWarning:objectError is empty!");
return null;
}
return objectError.getDefaultMessage();
}
17
View Source File : BaseController.java
License : Apache License 2.0
Project Creator : WeBankFinTech
License : Apache License 2.0
Project Creator : WeBankFinTech
private String getParamValidFaildMessage(BindingResult bindingResult) {
List<ObjectError> errorList = bindingResult.getAllErrors();
log.info("errorList:{}", JsonUtils.toJSONString(errorList));
if (errorList == null) {
log.warn("onWarning:errorList is empty!");
return null;
}
ObjectError objectError = errorList.get(0);
if (objectError == null) {
log.warn("onWarning:objectError is empty!");
return null;
}
return objectError.getDefaultMessage();
}
17
View Source File : WebExchangeBindException.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* Returns diagnostic information about the errors held in this object.
*/
@Override
public String getMessage() {
MethodParameter parameter = getMethodParameter();
replacedert.state(parameter != null, "No MethodParameter");
StringBuilder sb = new StringBuilder("Validation failed for argument at index ").append(parameter.getParameterIndex()).append(" in method: ").append(parameter.getExecutable().toGenericString()).append(", with ").append(this.bindingResult.getErrorCount()).append(" error(s): ");
for (ObjectError error : this.bindingResult.getAllErrors()) {
sb.append("[").append(error).append("] ");
}
return sb.toString();
}
17
View Source File : CouponController.java
License : MIT License
Project Creator : ShinJJang
License : MIT License
Project Creator : ShinJJang
@ResponseStatus(HttpStatus.CREATED)
@RequestMapping(value = "/coupon", method = RequestMethod.POST, consumes = "application/json; charset=UTF-8")
public Coupon createCoupon(@RequestBody @Valid CouponCreateDTO couponCreateDTO, BindingResult error) {
if (error.hasErrors()) {
for (ObjectError err : error.getAllErrors()) {
if (InvalidEmailException.errorCode.equals(err.getDefaultMessage())) {
log.info("CouponController - createCoupon : invalid email");
throw new InvalidEmailException("Fail to create Coupon. Email format is invalid.");
}
}
}
return couponService.create(couponCreateDTO);
}
17
View Source File : CustomRestExceptionHandler.java
License : Apache License 2.0
Project Creator : SAP
License : Apache License 2.0
Project Creator : SAP
@Override
protected ResponseEnreplacedy<Object> handleBindException(final BindException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) {
logger.info(ex.getClreplaced().getName());
//
final List<String> errors = new ArrayList<String>();
for (final FieldError error : ex.getBindingResult().getFieldErrors()) {
errors.add(error.getField() + ": " + error.getDefaultMessage());
}
for (final ObjectError error : ex.getBindingResult().getGlobalErrors()) {
errors.add(error.getObjectName() + ": " + error.getDefaultMessage());
}
final ApiError apiError = new ApiError(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), errors);
return handleExceptionInternal(ex, apiError, headers, apiError.getStatus(), request);
}
17
View Source File : CustomRestExceptionHandler.java
License : Apache License 2.0
Project Creator : SAP
License : Apache License 2.0
Project Creator : SAP
// 400
@Override
protected ResponseEnreplacedy<Object> handleMethodArgumentNotValid(final MethodArgumentNotValidException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) {
logger.info(ex.getClreplaced().getName());
//
final List<String> errors = new ArrayList<String>();
for (final FieldError error : ex.getBindingResult().getFieldErrors()) {
errors.add(error.getField() + ": " + error.getDefaultMessage());
}
for (final ObjectError error : ex.getBindingResult().getGlobalErrors()) {
errors.add(error.getObjectName() + ": " + error.getDefaultMessage());
}
final ApiError apiError = new ApiError(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), errors);
return handleExceptionInternal(ex, apiError, headers, apiError.getStatus(), request);
}
17
View Source File : AuthController.java
License : Apache License 2.0
Project Creator : roncoo
License : Apache License 2.0
Project Creator : roncoo
/**
* 获取错误返回信息
*
* @param bindingResult
* @return
*/
public String getErrorMsg(BindingResult bindingResult) {
StringBuffer sb = new StringBuffer();
for (ObjectError objectError : bindingResult.getAllErrors()) {
sb.append(objectError.getDefaultMessage()).append(",");
}
sb.delete(sb.length() - 1, sb.length());
return sb.toString();
}
17
View Source File : TaskDefineController.java
License : MIT License
Project Creator : hzwy23
License : MIT License
Project Creator : hzwy23
/*
* 新增任务组
* */
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
@ApiOperation(value = "新增任务信息", notes = "向系统中添加新的任务,任务必须是存储过程,shell脚本,cmd脚本,可执行jar包,二进制文件中的一种")
public String add(@Validated TaskDefineEnreplacedy taskDefineEnreplacedy, BindingResult bindingResult, HttpServletResponse response, HttpServletRequest request) {
// 校验参数信息
if (bindingResult.hasErrors()) {
for (ObjectError m : bindingResult.getAllErrors()) {
response.setStatus(421);
return Hret.error(421, m.getDefaultMessage(), null);
}
}
RetMsg retMsg = taskDefineService.add(parse(request));
if (retMsg.checkCode()) {
return Hret.success(retMsg);
}
response.setStatus(retMsg.getCode());
return Hret.error(retMsg);
}
See More Examples