Automapper processes custom exceptions, so it cannot handle them elsewhere

I throw custom exceptions inside my resolvers, but they are caught and wrapped by Automapper, so we cannot handle them elsewhere in the program. I included a simple example of the problem, the desired result is to catch an InterfaceError, but it only catches the AutoMapperException with the Errror interface as an internal exception.

In the class:

public Order MapOrder(InterfaceOrder iOrder)
{
    try
    {
        Order mappedOrder = Mapper.Map<InterfaceOrder, Order>(iOrder);
    }
    catch (InterfaceException ex)
    {
        Log("Interface error");
    }
    catch (Exception ex) 
    {
        Log("error");  
    }

    return mappedOrder;
}

Mapping:

Mapper.CreateMap<InterfaceOrder, Order>()                
      .ForMember(c => c.Name, op => op.ResolveUsing(data =>
        {
            if (Name.Length > 50) 
            { 
                throw new InterfaceException("Error!", ex);                                                                   
            }
            else 
            {
                return c.Name
            }
        }));
+5
source share
2 answers

Automapper , , . Map , AutoMapperMappingException

public ToClass Map<FromClass, ToClass>(FromClass fc)
{
    try
    {
        return Mapper.Map<FromClass, ToClass>(fc);
    }
    catch(AutoMapperMappingException autoMapperException)
    {
        throw autoMapperException.InnerException; 
        // this will break your call stack
        // you may not know where the error is called and rather
        // want to clone the InnerException or throw a brand new Exception
    }
}
+4

. ForMember(...MapFrom(...)) , ForMember(...MapFrom(...)). AfterMap(...) AfterMap(...), AfterMap(...).

0

Source: https://habr.com/ru/post/1531804/


All Articles