/// <summary> /// Loop through the innerexceptions and get the first one which is not a AutoMapperMappingException instance. /// </summary> /// <param name="memberMapException">The high-level exception.</param> /// <returns>The inner exception that is not a instance if any.</returns> private static Exception GetRegularException(AutoMapperMappingException memberMapException) { Exception underlyingException = memberMapException; while (underlyingException is AutoMapperMappingException && (underlyingException.InnerException != null)) { underlyingException = underlyingException.InnerException; } return(underlyingException); }
/// <summary> /// Loop through the innerexceptions and get the first one with a IMemberMap instance. /// </summary> /// <param name="mappingException">The high-level exception.</param> /// <returns>The inner exception with a IMemberMap instance if any.</returns> private static AutoMapperMappingException GetMemberMapException(AutoMapperMappingException mappingException) { AutoMapperMappingException memberMapException = mappingException; while (memberMapException.MemberMap == null && memberMapException.InnerException is AutoMapperMappingException) { memberMapException = memberMapException.InnerException as AutoMapperMappingException; } return(memberMapException); }
private static ErrorResponse ExtractErrorResponseFromContext(ExceptionContext context) { return(context.Exception switch { AutoMapperMappingException mappingException => mappingException.CreateErrorResponse(), DomainException domainException => domainException.CreateErrorResponse(), BusinessException businessException => businessException.CreateErrorResponse(), AuthorizationConfigException authorizationConfigException => authorizationConfigException.CreateErrorResponse(), UnauthorizedAccessException unauthorizedAccessException => unauthorizedAccessException.CreateErrorResponse(), _ => context.Exception.CreateErrorResponse() });
/// <summary> /// Translates the AutoMapperMappingException to a ExcelToObjectMapperException /// </summary> /// <param name="mappingException">The exception to be translated</param> /// <returns>The translated exception.</returns> private ExcelToObjectException TranslateException(AutoMapperMappingException mappingException) { AutoMapperMappingException memberMapException = GetMemberMapException(mappingException); Exception regularException = GetRegularException(memberMapException); if (memberMapException.TypeMap.SourceType == typeof(DataSet) && memberMapException.TypeMap.CustomCtorExpression != null) { return(new ExcelToObjectException($"Cannot map {memberMapException.TypeMap.CustomCtorExpression.Body} to a DataTable: {regularException.Message}")); } else if (memberMapException.TypeMap.SourceType == typeof(DataRow) && memberMapException.MemberMap.CustomMapExpression.Body != null) { return(new ExcelToObjectException($"Cannot map {memberMapException.MemberMap.CustomMapExpression.Body} to {memberMapException.MemberMap.DestinationName}: {regularException.Message}")); } return(new ExcelToObjectException(memberMapException.Message)); }
public void Should_have_contextual_mapping_information() { var source = new Source { Value = "adsf" }; AutoMapperMappingException thrown = null; try { Mapper.Map <Source, Dest>(source); } catch (AutoMapperMappingException ex) { thrown = ex; } thrown.ShouldNotBeNull(); }
public static ErrorResponse CreateErrorResponse(this AutoMapperMappingException ex) { var error = "Error in mapping invalid data"; var validationError = ex?.InnerException?.InnerException?.Message; if (validationError == null) { validationError = ex?.InnerException?.Message; } if (validationError != null) { error = error + " - " + validationError; } return(new ErrorResponse(error, HttpStatusCode.BadRequest, null)); }
public void Should_have_contextual_mapping_information() { var source = new Source { Value = "adsf" }; AutoMapperMappingException thrown = null; try { Mapper.Map <Source, Dest>(source); } catch (AutoMapperMappingException ex) { thrown = ex; } thrown.ShouldNotBeNull(); thrown.InnerException.ShouldNotBeNull(); thrown.InnerException.ShouldBeType <AutoMapperMappingException>(); ((AutoMapperMappingException)thrown.InnerException).Context.PropertyMap.ShouldNotBeNull(); }
public Task OnExceptionAsync(ExceptionContext context) { _logger.LogError(context.Exception, context.Exception.Message); context.Result = context.Exception switch { AutoMapperMappingException e => new BadRequestObjectResult( new ProblemDetails { Title = "Mapping or parsing error", Detail = e.InnerException?.Message ?? e.Message }), ArgumentException e => new BadRequestObjectResult(new ProblemDetails { Title = "Invalid value", Detail = e.Message }), Exception e => new ObjectResult(new ProblemDetails { Title = "Error", Detail = "An error occured while processing the request", Status = StatusCodes.Status500InternalServerError }) }; return(Task.CompletedTask); } }
private void MapPropertyValue(ResolutionContext context, IMappingEngineRunner mapper, object mappedObject, PropertyMap propertyMap) { if (!propertyMap.CanResolveValue() || !propertyMap.ShouldAssignValuePreResolving(context)) { return; } ResolutionResult result; Exception resolvingExc = null; try { result = propertyMap.ResolveValue(context); } catch (AutoMapperMappingException) { throw; } catch (Exception ex) { var errorContext = CreateErrorContext(context, propertyMap, null); resolvingExc = new AutoMapperMappingException(errorContext, ex); result = new ResolutionResult(context); } if (result.ShouldIgnore) { return; } object destinationValue = propertyMap.GetDestinationValue(mappedObject); var sourceType = result.Type; var destinationType = propertyMap.DestinationProperty.MemberType; var typeMap = mapper.ConfigurationProvider.ResolveTypeMap(result, destinationType); Type targetSourceType = typeMap != null ? typeMap.SourceType : sourceType; var newContext = context.CreateMemberContext(typeMap, result.Value, destinationValue, targetSourceType, propertyMap); if (!propertyMap.ShouldAssignValue(newContext)) { return; } // If condition succeeded and resolving failed, throw if (resolvingExc != null) { throw resolvingExc; } try { object propertyValueToAssign = mapper.Map(newContext); AssignValue(propertyMap, mappedObject, propertyValueToAssign); } catch (AutoMapperMappingException) { throw; } catch (Exception ex) { throw new AutoMapperMappingException(newContext, ex); } }
private void MapPropertyValue(ResolutionContext context, IMappingEngineRunner mapper, object mappedObject, PropertyMap propertyMap) { if (propertyMap.CanResolveValue() && propertyMap.ShouldAssignValuePreResolving(context)) { ResolutionResult result; Exception resolvingExc = null; try { result = propertyMap.ResolveValue(context); } catch (AutoMapperMappingException) { throw; } catch (Exception ex) { var errorContext = CreateErrorContext(context, propertyMap, null); resolvingExc = new AutoMapperMappingException(errorContext, ex); result = new ResolutionResult(context); } if (result.ShouldIgnore) return; object destinationValue = propertyMap.GetDestinationValue(mappedObject); var sourceType = result.Type; var destinationType = propertyMap.DestinationProperty.MemberType; var typeMap = mapper.ConfigurationProvider.FindTypeMapFor(result, destinationType); Type targetSourceType = typeMap != null ? typeMap.SourceType : sourceType; var newContext = context.CreateMemberContext(typeMap, result.Value, destinationValue, targetSourceType, propertyMap); if (!propertyMap.ShouldAssignValue(newContext)) return; // If condition succeeded and resolving failed, throw if (resolvingExc != null) throw resolvingExc; try { object propertyValueToAssign = mapper.Map(newContext); AssignValue(propertyMap, mappedObject, propertyValueToAssign); } catch (AutoMapperMappingException) { throw; } catch (Exception ex) { throw new AutoMapperMappingException(newContext, ex); } } }
public void Should_provide_a_useful_message() { var ex = new AutoMapperMappingException(); ex.Message.ShouldStartWith("Exception"); }
private object CreateMappingErrorResponse(AutoMapperMappingException mappingException) { return(new { Error = "InvalidRequest", ModelErrors = new { Fields = mappingException.FailedFields() } }); }
/// <summary> /// Initializes a new instance of the <see cref="CommandArgumentMapException"/> class. /// </summary> /// <param name="parameterIndex">Index of the parameter that failed to map.</param> /// <param name="autoMapperMappingException">Inner exception of this exception.</param> public CommandArgumentMapException(int parameterIndex, AutoMapperMappingException autoMapperMappingException) : base($"Unable to map parameter \"{parameterIndex}\" to {autoMapperMappingException.Types?.DestinationType}", autoMapperMappingException) { this.ParameterIndex = parameterIndex; }
public async override void OnException(ExceptionContext context) { string errorMessage; if (context.Exception.InnerException != null) { errorMessage = $"{context.Exception.InnerException}"; if (typeof(AutoMapperMappingException) == context.Exception.InnerException.GetType()) { AutoMapperMappingException errorAutomapper = (AutoMapperMappingException)context.Exception.InnerException; errorMessage = $"Error: {errorAutomapper} origen: {errorAutomapper.MemberMap.SourceMember.Name}. " + $"Destino:{errorAutomapper.MemberMap.DestinationName}"; } } else { errorMessage = $"{context.Exception.Message}"; //- {context.Exception.StackTrace}"; } logger.Fatal(errorMessage); ClienteResponse response = new ClienteResponse("", 0, "") { }; switch (context.Exception.GetType().ToString()) { case "APINosis.Helpers.NotFoundException": response.Estado = 404; response.Titulo = "Not Found"; response.IdOperacion = 0; response.Mensaje = "El recurso solicitado no fue encontrado"; context.Result = new NotFoundObjectResult(response); context.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound; break; case "APINosis.Helpers.BadRequestException": response.Estado = 400; response.Titulo = "Bad Request"; response.IdOperacion = 0; response.Mensaje = errorMessage; context.Result = new NotFoundObjectResult(response); context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; break; default: response.Estado = 500; response.Titulo = "Error interno de la aplicaciĆ³n"; response.Mensaje = errorMessage; response.IdOperacion = 0; context.Result = new ObjectResult(response); context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError; break; } context.ExceptionHandled = true; }
public static object FailedFields(this AutoMapperMappingException mappingException) { return(mappingException.MemberMap.SourceMembers.Select(x => x.Name).ToList()); }