1 /*
2  * Copyright 2002-2011 the original author or authors.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package org.springframework.web.bind;
18 
19 import org.springframework.core.MethodParameter;
20 import org.springframework.validation.BindingResult;
21 import org.springframework.validation.ObjectError;
22 
23 /**
24  * Exception to be thrown when validation on an argument annotated with {@code @Valid} fails.
25  *
26  * @author Rossen Stoyanchev
27  * @since 3.1
28  */
29 public class MethodArgumentNotValidException extends Exception {
30 
31 	private final MethodParameter parameter;
32 
33 	private final BindingResult bindingResult;
34 
35 
36 	/**
37 	 * Constructor for {@link MethodArgumentNotValidException}.
38 	 * @param parameter the parameter that failed validation
39 	 * @param bindingResult the results of the validation
40 	 */
MethodArgumentNotValidException(MethodParameter parameter, BindingResult bindingResult)41 	public MethodArgumentNotValidException(MethodParameter parameter, BindingResult bindingResult) {
42 		this.parameter = parameter;
43 		this.bindingResult = bindingResult;
44 	}
45 
46 	/**
47 	 * Return the method parameter that failed validation.
48 	 */
getParameter()49 	public MethodParameter getParameter() {
50 		return this.parameter;
51 	}
52 
53 	/**
54 	 * Return the results of the failed validation.
55 	 */
getBindingResult()56 	public BindingResult getBindingResult() {
57 		return this.bindingResult;
58 	}
59 
60 
61 	@Override
getMessage()62 	public String getMessage() {
63 		StringBuilder sb = new StringBuilder("Validation failed for argument at index ")
64 			.append(this.parameter.getParameterIndex()).append(" in method: ")
65 			.append(this.parameter.getMethod().toGenericString())
66 			.append(", with ").append(this.bindingResult.getErrorCount()).append(" error(s): ");
67 		for (ObjectError error : this.bindingResult.getAllErrors()) {
68 			sb.append("[").append(error).append("] ");
69 		}
70 		return sb.toString();
71 	}
72 
73 }
74