如何在返回Task <Something>的异步方法中处理异常

时间:2020-06-26 15:15:49

标签: c# async-await task

我很想在中间件层中引入异常日志记录。从该中间件的顶部到底部,调用如下:

//In layer C
public async Task<List<Foo>> GetFoo(GetFooRequest request)
{
    return await _repository.GetFooAsync(request);
} 

//In layer D
public async Task<List<Foo>> GetFooAsync(GetFooRequest request)
{
    return await _context.Foo.Where(x=> x.FooId=request.FooID).ToListAsync();
} 

我想登录C层,但是Task返回了System.Void,因此编译器抱怨下面的代码。我理解下面的代码为什么会失败,但是在找到解决方案模式或登录C层的实践时遇到了问题。

 //In layer C
public async Task<List<Foo>> GetFoo(GetFooRequest request)
{
    try
    {
        return await _repository.GetFooAsync(request);
    }
    catch(Exception e)
    {
        base.LogException(e)      //<- Not all code paths return a value
    }
} 

有没有一种方法可以创建一个调用方法并在其中进行记录的类,例如return await LogInvoker.Invoke(_repository.GetFooAsync...)?还是这需要重构各层之间的电流?

1 个答案:

答案 0 :(得分:1)

您必须在catch块的末尾做一些事情。您在问题注释中提到,如果出现问题,您准备返回一个空列表:

public async Task<List<Foo>> GetFoo(GetFooRequest request)
{
    try
    {
        return await _repository.GetFooAsync(request);
    }
    catch(Exception e)
    {
        base.LogException(e);
        return new List<Foo>();
    }
} 

或重新抛出异常(如果对您的应用程序有意义):

public async Task<List<Foo>> GetFoo(GetFooRequest request)
{
    try
    {
        return await _repository.GetFooAsync(request);
    }
    catch(Exception e)
    {
        base.LogException(e);
        throw;
    }
} 
相关问题