Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

c# - 如何存储大量异常,然后作为Web API的响应返回?(How can I store a bunch of exceptions and return then as the response of an web API?)

So I'm trying to import a bunch of data from an excel to a DB in my Web Api, this data is being validate using FluentValidation , 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.

(所以我试图将一堆数据从excel导入到我的Web Api中的数据库,该数据正在使用FluentValidation进行验证,问题是,每当我从excel表中看到一条包含不良信息的行时,我的代码就会停止正在运行,API返回异常。)

I wish I could store all these exceptions, keep my code running until the end of the excel table, and then after that return all the exceptions as my API response.

(我希望可以存储所有这些异常,使代码一直运行到excel表的末尾,然后在此之后将所有异常作为我的API响应返回。)

I also think it would be a good idea to return in which line of the table the expetion ocurred.

(我还认为最好返回表发生在表的哪一行。)

My code is running inside a for each statement so for storing the line in wich errors ocurred I can simply start a counter inside of it.

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

As for keeping my code running I can run it inside of a Try-Catch (or would there be a better way?), but inside of it how can I store all the exceptions togueter to then return them later?

(至于让我的代码保持运行,我可以在Try-Catch内部运行它(或者会有更好的方法吗?),但是在其中如何存储所有异常,然后再返回呢?)

  ask by Rogerio Schmitt translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Most .NET parts that can return multiple exceptions use AggregateException to achieve that.

(可以返回多个异常的大多数.NET部件都使用AggregateException来实现。)

A generic template for that would be:

(一个通用的模板是:)

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

Here's the docs for AggregateException .

(这是AggregateException的文档 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...