我在我的解析器中抛出自定义异常,但它们被Automapper捕获并包装,所以我们无法在程序的其他地方处理它们。我已经包含了一个简单的问题示例,期望的结果是捕获一个InterfaceError,但它只捕获一个AutoMapperException,并将InterfaceError作为内部异常。
在班上:
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;
}
制图:
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
}
}));
Automapper不会让异常直接从映射过程中转义,但会在您注意到的情况下尝试将其包装在自己的Exception中。你最好的选择是在一个捕捉AutoMapperMappingException
并解开它的函数中包含对Map的调用
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
}
}
一个有趣的说明。如果从ForMember(...MapFrom(...))
调用抛出异常,则只会发生异常的包装。如果在AfterMap(...)
中抛出相同的异常,则它不会被包装。