mohan
mohan

Reputation: 1

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. 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. How can I do this?

Upvotes: 0

Views: 1182

Answers (1)

NazaRN
NazaRN

Reputation: 419

Well, to validate your CreateAccountPayload you can do the following.

A. You can indeed throw the AggregateException but first you need to add your exceptions to the list.

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

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

B. Another option might be the following. You can add your messages (not throwing exceptions) to a List of strings, and return it. And if the list is empty - validation passed.

Upvotes: 2

Related Questions