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