001/*
002 * Copyright 2002-2017 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.messaging.handler.annotation.support;
018
019import org.springframework.core.MethodParameter;
020import org.springframework.messaging.Message;
021import org.springframework.validation.BindingResult;
022import org.springframework.validation.ObjectError;
023
024/**
025 * Exception to be thrown when a method argument fails validation perhaps as a
026 * result of {@code @Valid} style validation, or perhaps because it is required.
027 *
028 * @author Brian Clozel
029 * @author Rossen Stoyanchev
030 * @since 4.0.1
031 */
032@SuppressWarnings({"serial", "deprecation"})
033public class MethodArgumentNotValidException extends AbstractMethodArgumentResolutionException {
034
035        private BindingResult bindingResult;
036
037
038        /**
039         * Create a new instance with the invalid {@code MethodParameter}.
040         */
041        public MethodArgumentNotValidException(Message<?> message, MethodParameter parameter) {
042                super(message, parameter);
043        }
044
045        /**
046         * Create a new instance with the invalid {@code MethodParameter} and a
047         * {@link org.springframework.validation.BindingResult}.
048         */
049        public MethodArgumentNotValidException(Message<?> message, MethodParameter parameter, BindingResult bindingResult) {
050                super(message, parameter, getValidationErrorMessage(bindingResult));
051                this.bindingResult = bindingResult;
052        }
053
054
055        /**
056         * Return the BindingResult if the failure is validation-related,
057         * or {@code null} if none.
058         */
059        public final BindingResult getBindingResult() {
060                return this.bindingResult;
061        }
062
063
064        private static String getValidationErrorMessage(BindingResult bindingResult) {
065                StringBuilder sb = new StringBuilder();
066                sb.append(bindingResult.getErrorCount()).append(" error(s): ");
067                for (ObjectError error : bindingResult.getAllErrors()) {
068                        sb.append("[").append(error).append("] ");
069                }
070                return sb.toString();
071        }
072
073}