001/* 002 * Copyright 2002-2012 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.web.bind; 018 019import org.springframework.core.MethodParameter; 020import org.springframework.validation.BindingResult; 021import org.springframework.validation.ObjectError; 022 023/** 024 * Exception to be thrown when validation on an argument annotated with {@code @Valid} fails. 025 * 026 * @author Rossen Stoyanchev 027 * @since 3.1 028 */ 029@SuppressWarnings("serial") 030public class MethodArgumentNotValidException extends Exception { 031 032 private final MethodParameter parameter; 033 034 private final BindingResult bindingResult; 035 036 037 /** 038 * Constructor for {@link MethodArgumentNotValidException}. 039 * @param parameter the parameter that failed validation 040 * @param bindingResult the results of the validation 041 */ 042 public MethodArgumentNotValidException(MethodParameter parameter, BindingResult bindingResult) { 043 this.parameter = parameter; 044 this.bindingResult = bindingResult; 045 } 046 047 /** 048 * Return the method parameter that failed validation. 049 */ 050 public MethodParameter getParameter() { 051 return this.parameter; 052 } 053 054 /** 055 * Return the results of the failed validation. 056 */ 057 public BindingResult getBindingResult() { 058 return this.bindingResult; 059 } 060 061 062 @Override 063 public String getMessage() { 064 StringBuilder sb = new StringBuilder("Validation failed for argument at index ") 065 .append(this.parameter.getParameterIndex()).append(" in method: ") 066 .append(this.parameter.getMethod().toGenericString()) 067 .append(", with ").append(this.bindingResult.getErrorCount()).append(" error(s): "); 068 for (ObjectError error : this.bindingResult.getAllErrors()) { 069 sb.append("[").append(error).append("] "); 070 } 071 return sb.toString(); 072 } 073 074}