gpt4 book ai didi

c# - 如何在实际迭代发生之前验证 IAsyncEnumerable 返回方法的参数?

转载 作者:行者123 更新时间:2023-12-04 03:58:26 28 4
gpt4 key购买 nike

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

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);}
}

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

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

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

最佳答案

将其拆分为两个函数。 Here的一个例子:

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);
}
}
}

关于c# - 如何在实际迭代发生之前验证 IAsyncEnumerable 返回方法的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63493334/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com