有没有办法禁用AutoMapper的异常包装?

Dan*_* T. 6 c# exception-handling exception wrapper automapper

我有一个存储库,EntityNotFoundException当它的GetSingle<T>(int id)方法无法在数据库中找到所请求的实体时会抛出一个存储库.当我在AutoMapper中使用它并发生异常时,我会得到类似的东西:

AutoMapperMappingException:尝试将CategoryDTO映射到Category ... --->

AutoMapperMappingException:尝试将System.Int32映射到CategoryType ... --->

AutoMapper.MappingException:尝试将System.Int32映射到CategoryType ... --->

EntityNotFoundException:在数据库中找不到ID为5的TypeType类型的实体

我的自定义异常是4级.这使得很难使用try-catch块,因为现在我必须做这样的事情:

try
{
    // do the mapping
}
catch (AutoMapperMappingException e)
{
    // get the inner-most exception
    while (e.InnerException != null)
    {
        e = e.InnerException;
    }

    // check to see if it's an EntityNotFoundException
    if (e.GetType() == typeof (EntityNotFoundException))
    {
        var notFound = e as EntityNotFoundException;
        // do something specific here, like inform the user
    }
    else
    {
        // do something more generic
    }
Run Code Online (Sandbox Code Playgroud)

我希望能做的就是这样:

try
{
    // do the mapping
}
catch (EntityNotFoundException e)
{
    // do something specific here, like inform the user
}
catch (Exception e)
{
    // do something more generic
}
Run Code Online (Sandbox Code Playgroud)

有没有办法禁用AutoMapper的异常包装行为,以便我得到抛出的直接异常?

回答

我最终创建了一个瘦的包装器AutoMapper,它将捕获AutoMapperMappingException,找到最内部的异常,并抛出:

public class AutoMapperWrapper
{
    public TB Map<TA, TB>(TA source, TB destination)
    {
        // try to do the mapping
        try
        {
            return Mapper.Map(source, destination);
        }
        // catch AutoMapper's exception
        catch (Exception e)
        {
            // find the first InnerException that's not wrapped
            while (e is AutoMapperMappingException)
            {
                e = e.InnerException;
            }

            // if the inner exception is null, throw the original exception
            if (e == null)
            {
                throw;
            }
            // otherwise, throw the inner exception
            else
            {
                throw e;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这种方法的缺点是,有时候整个异常树看起来很有用,看看AutoMapper的哪个属性或实体映射失败,但是这段代码只会给你最内部的异常,有时它本身并不是很有用. ,像InvalidCastException:"无法将字符串转换为int",但不会告诉你它是哪个属性.

Vde*_*edT 1

我认为有条件地包装异常是一个糟糕的设计,所以我想唯一要做的就是深入到内部异常并找到第一个 none automapperexception。