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.core.convert;
018
019import org.springframework.lang.Nullable;
020import org.springframework.util.ObjectUtils;
021
022/**
023 * Exception to be thrown when an actual type conversion attempt fails.
024 *
025 * @author Keith Donald
026 * @author Juergen Hoeller
027 * @since 3.0
028 */
029@SuppressWarnings("serial")
030public class ConversionFailedException extends ConversionException {
031
032        @Nullable
033        private final TypeDescriptor sourceType;
034
035        private final TypeDescriptor targetType;
036
037        @Nullable
038        private final Object value;
039
040
041        /**
042         * Create a new conversion exception.
043         * @param sourceType the value's original type
044         * @param targetType the value's target type
045         * @param value the value we tried to convert
046         * @param cause the cause of the conversion failure
047         */
048        public ConversionFailedException(@Nullable TypeDescriptor sourceType, TypeDescriptor targetType,
049                        @Nullable Object value, Throwable cause) {
050
051                super("Failed to convert from type [" + sourceType + "] to type [" + targetType +
052                                "] for value '" + ObjectUtils.nullSafeToString(value) + "'", cause);
053                this.sourceType = sourceType;
054                this.targetType = targetType;
055                this.value = value;
056        }
057
058
059        /**
060         * Return the source type we tried to convert the value from.
061         */
062        @Nullable
063        public TypeDescriptor getSourceType() {
064                return this.sourceType;
065        }
066
067        /**
068         * Return the target type we tried to convert the value to.
069         */
070        public TypeDescriptor getTargetType() {
071                return this.targetType;
072        }
073
074        /**
075         * Return the offending value.
076         */
077        @Nullable
078        public Object getValue() {
079                return this.value;
080        }
081
082}