我如何存储一堆异常,然后 return 作为网络 API 的响应?

How can I store a bunch of exceptions and return then as the response of an web API?

我正在尝试将一堆数据从 Excel 导入我的 Web API 中的数据库,这些数据正在使用 FluentValidation 进行验证,问题是,每次我遇到来自 Excel table 的错误信息时,我的代码停止 运行ning 并且 API returns 异常。

我希望我可以存储所有这些异常,将我的代码 运行ning 保留到 Excel table 结束,然后 return 所有作为我的 API 回复的例外情况。我还认为 return 在 table 的哪一行发生异常是个好主意。

我的代码 运行ning 在每个语句中,因此为了存储发生错误的行,我可以简单地在其中启动一个计数器。

至于保存我的代码 运行ning 我可以 运行 它在 Try-Catch 中(或者有更好的方法吗?),但在它里面我如何存储所有例外一起 return 他们稍后?

大多数可以 return 多个异常的 .NET 部分使用 AggregateException 来实现。一个通用模板是:

var exceptions = new List<Exception>();

foreach (var w in work)
{
    try
    {
        DoWork(w);
    }
    catch (Exception e)
    {
        exceptions.Add(e);
    }
}

if (exceptions.Any())
{
    throw new AggregateException(exceptions);
}

这里是the docs for AggregateException

the problem is, every time I hit a line with bad information from the excel table my code stops running and the API returns the exception.

在异常发生后继续处理从来都不是一个好主意。充其量您正在使用的东西现在处于无效状态,并且每次进一步的访问尝试都会抛出更多异常"InvalidState"。在最坏的情况下,它会完全崩溃并且会导致完全不可预测的行为,因为它假设你不会做这么糟糕的事情。由于内存访问冲突,此类行为可能会一直进入您的进程,并被 windows 踢出。

basic classification 我用于异常。虽然此异常在最坏的情况下对于您的代码来说是外生异常,但对于解析器和此 Documet 而言,它应该被视为致命异常。继续下去,不会增加任何价值。充其量,它会添加更多无用的错误消息来隐藏真正的错误。

90% 的编译器错误都是因为语法错误。而且它常常是错误的,源代码解析器无法再对它所看到的内容做出正面或反面的判断。它甚至无法告诉您 问题出在哪里

你应该expose/log每个异常,在第一个异常之后停止解析并让用户处理问题(这显然不在你的工作范围内)。

您可以尝试在 excel table 中添加一个额外的状态列,例如,您可以调整您的逻辑并存储在 excel table 中存储进入数据库。

class Program
{
    static void Main(string[] args)
    {
        Customer Cust = new Customer();
        List<Customer> Customers = Cust.GetCustomers();

        foreach(Customer c in Customers)
        {
            Console.WriteLine(c.Name);
        }

        Console.Read();
    }
}

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }

    public string  Status { get; set; }
    List<Customer> Customers = new List<Customer>();

    public  List<Customer> GetCustomers()
    { 
        //Your Foreach Logic will be replaced
    for(int i=0;i<3;i++)
        {
            if (i % 2 == 0)
            {
                Customers.Add(new Customer { Id = i, Name = "Name" + i, Status = "Success Message" });
            }
            else
            {
                Customers.Add(new Customer { Id = i, Name = "Name" + i, Status = "Error Message" });

            }


        }

        return Customers;
    }
}