繁体   English   中英

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

[英]How to handle exceptions in async methods that return Task<Something>

我被要求在中间件层中引入异常日志记录。 从上到下这个中间件的调用如下:

//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
    }
} 

有没有办法可以创建一个调用方法并在那里进行日志记录的 class,例如 return await LogInvoker.Invoke(_repository.GetFooAsync...) 或者这是否需要重构层之间的电流?

你必须在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;
    }
} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM