How to parse AutoMapper exceptions for error logs table? #3663
-
Sorry for a clumsy title, but it's descriptive. I am mapping a single object/record at a time to ensure I get the exception, but exploring the AutoMapperMappingException type, it's a jungle of information. What I want is a simple one row per property/field when something goes wrong, that can be customer readable. I would have expected there to be a ton of libraries to facilitate this, or some docs but I can't find anything. Here's my little extension method to extract the exception: public static AutoMapperResult<T> TryMap<T, TValue>(this IMapper mapper, TValue value)
{
var output = new AutoMapperResult<T>();
try
{
output.Data = mapper.Map<TValue, T>(value);
output.Success = true;
}
catch (AutoMapperMappingException mappingException)
{
output.MappingException = mappingException;
}
return output;
} here's how I map it to my internal entity, (or rather two of the lines referencing the type name works fine, but I want member/property names, and those examples only return "null"): public class MappingExceptionProfile : Profile
{
public MappingExceptionProfile()
{
CreateMap<AutoMapperMappingException, MappingException>()
.ForMember(x => x.DestinationProperty, opt => opt.MapFrom(y => y.Types.Value.GetRelatedTypePairs().FirstOrDefault().DestinationType.Name))
.ForMember(x => x.DestinationProperty, opt => opt.MapFrom(y => y.MemberMap.DestinationName))
.ForMember(x => x.SourceProperty, opt => opt.MapFrom(y => y.Types.Value.GetRelatedTypePairs().FirstOrDefault().SourceType.Name))
.ForMember(x => x.SourceProperty, opt => opt.MapFrom(y => y.MemberMap.SourceMember.Name))
.ForMember(x => x.ErrorMessage, opt => opt.MapFrom(y => y.Message))
.ForMember(x => x.DateTime, opt => opt.MapFrom(y => DateTime.UtcNow))
.ForMember(x => x.Severity, opt => opt.MapFrom(y => Severity.Error))
;
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
You should look at how the error message is composed. And write some tests :) These are internal details that we're not going to document. |
Beta Was this translation helpful? Give feedback.
You should look at how the error message is composed. And write some tests :) These are internal details that we're not going to document.