简体   繁体   English

如何从 ArgumentException 中列出 <> 异常并抛出 AggregateException

[英]How to List<> of exceptions from ArgumentException and throw a AggregateException

private void AccountValidations(CreateAccountPayload payload) {
  if (string.IsNullOrEmpty(payload.Note)) {
    throw new ArgumentException($ "Note cannot be empty");
  }
  if (string.IsNullOrEmpty(payload.AccountName)) {
    throw new ArgumentException($ "Account Name cnnot be Empty");
  }
  if (string.IsNullOrEmpty(payload.Type)) {
    throw new ArgumentException($ "Account Type cnnot be Empty");
  }
}

I want all the exception messages at once, eg: In the payload object if I don't provide AccountName and Note .我想要一次所有异常消息,例如:如果我不提供AccountNameNote ,则在有效负载 object 中。 It should report me both Note cannot be empty and Account Name can not be Empty How can I do that?它应该报告我注意不能为空帐户名称不能为空我该怎么做?

I thought of making a List of all these messages and then throw a Agregateexception .我想制作一个包含所有这些消息的列表,然后抛出一个Agregateexception How can I do this?我怎样才能做到这一点?

Well, to validate your CreateAccountPayload you can do the following.那么,要验证您的CreateAccountPayload ,您可以执行以下操作。

A. You can indeed throw the AggregateException but first you need to add your exceptions to the list. A. 你确实可以抛出AggregateException但首先你需要将你的异常添加到列表中。

var exceptions = new List<Exception>();
if (string.IsNullOrEmpty(payload.Note)) {
exceptions.Add(new ArgumentException($ "Note cannot be empty"));
}
 if (string.IsNullOrEmpty(payload.AccountName)) {
exceptions.Add(new ArgumentException($ "Account Name cnnot be Empty"));
}
if (string.IsNullOrEmpty(payload.Type)) {
exceptions.Add(new ArgumentException($ "Account Type cnnot be Empty"));
}
if (exceptions.Any()) throw new AggregateException(
    "Encountered errors while validating.",
    exceptions);

The outer code should catch the exception.外部代码应该捕获异常。

catch (AggregateException e)

You just need to inspect the InnerExceptions property and construct the errors string like this您只需要检查InnerExceptions属性并像这样构造错误字符串

string.Join(" and ", e.InnerExceptions.Select(ex => ex.Message));

B. Another option might be the following. B. 另一种选择可能如下。 You can add your messages (not throwing exceptions) to a List of strings, and return it.您可以将消息(不抛出异常)添加到字符串列表中,然后将其返回。 And if the list is empty - validation passed.如果列表为空 - 验证通过。

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

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