@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); }
@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; } }
@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 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); }
/** * 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(); }
/** * Binds the given source object to the given target object performing type conversion if * necessary * * @param domain The GrailsDomainClass instance * @param object The object to bind to * @param source The source object * @param include The list of properties to include * @param exclude The list of properties to exclude * @param filter The prefix to filter by * @see grails.core.GrailsDomainClass * @return A BindingResult or null if it wasn't successful */ @SuppressWarnings("unchecked") public static BindingResult bindObjectToDomainInstance( GrailsDomainClass domain, Object object, Object source, List include, List exclude, String filter) { BindingResult bindingResult = null; GrailsApplication grailsApplication = null; if (domain != null) { grailsApplication = domain.getApplication(); } if (grailsApplication == null) { grailsApplication = Holders.findApplication(); } try { final DataBindingSource bindingSource = createDataBindingSource(grailsApplication, object.getClass(), source); final DataBinder grailsWebDataBinder = getGrailsWebDataBinder(grailsApplication); grailsWebDataBinder.bind(object, bindingSource, filter, include, exclude); } catch (InvalidRequestBodyException e) { String messageCode = "invalidRequestBody"; Class objectType = object.getClass(); String defaultMessage = "An error occurred parsing the body of the request"; String[] codes = getMessageCodes(messageCode, objectType); bindingResult = new BeanPropertyBindingResult(object, objectType.getName()); bindingResult.addError( new ObjectError(bindingResult.getObjectName(), codes, null, defaultMessage)); } catch (Exception e) { bindingResult = new BeanPropertyBindingResult(object, object.getClass().getName()); bindingResult.addError(new ObjectError(bindingResult.getObjectName(), e.getMessage())); } if (domain != null && bindingResult != null) { BindingResult newResult = new ValidationErrors(object); for (Object error : bindingResult.getAllErrors()) { if (error instanceof FieldError) { FieldError fieldError = (FieldError) error; final boolean isBlank = BLANK.equals(fieldError.getRejectedValue()); if (!isBlank) { newResult.addError(fieldError); } else if (domain.hasPersistentProperty(fieldError.getField())) { final boolean isOptional = domain.getPropertyByName(fieldError.getField()).isOptional(); if (!isOptional) { newResult.addError(fieldError); } } else { newResult.addError(fieldError); } } else { newResult.addError((ObjectError) error); } } bindingResult = newResult; } MetaClass mc = GroovySystem.getMetaClassRegistry().getMetaClass(object.getClass()); if (mc.hasProperty(object, "errors") != null && bindingResult != null) { ValidationErrors errors = new ValidationErrors(object); errors.addAllErrors(bindingResult); mc.setProperty(object, "errors", errors); } return bindingResult; }