3

我有一个简单的场景,我有一个具有以下方法的类:

public async IAsyncEnumerable<Entity> GetEntities(IQueryOptions options){
  if(!validator.ValidateQuery(options)) { throw new ArgumentException(nameof(options));}

  var data = dataSource.ReadEntitiesAsync(options);

  await foreach (var entity in data) { yield return await converter.ConvertAsync(entity);}
}

是否可以ArgumentException在方法调用时准确地抛出GetEntities(),而不是在迭代的第一步之后,像这里:

await foreach(var e in GetEntities(options)) { // some code here }

我问是因为当我想返回IAsyncEnumerable到我的 API 控制器时,异常实际上是在框架代码中引发的。我没有机会抓住它,并返回一个 HTTP 404 BAD REQUEST 代码。当然,我可以在请求管道中拦截异常,但有时我想根据它们来自的抽象层将它们包装在其他异常中。

4

1 回答 1

1

将其拆分为两个功能。是一个例子:

using System;
using System.Threading.Tasks;
using System.Collections.Generic;
                    
public class Program
{
    public static async Task Main()
    {
        var enumeration = AsyncEnumeration(-1);
        await foreach(int x in enumeration)
        {
            Console.WriteLine(x);
        }
    }
    
    public static IAsyncEnumerable<int> AsyncEnumeration(int count)
    {
        if (count < 1)
            throw new ArgumentOutOfRangeException();
        
        return AsyncEnumerationCore(count);
    }
    
    private static async IAsyncEnumerable<int> AsyncEnumerationCore(int count)
    {
        for (int i = 0; i < count; i++)
        {
            yield return i;
            await Task.Delay(1);
        }
    }
}
于 2020-08-19T19:06:12.477 回答