0
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?

Master.Deep
  • 792
  • 5
  • 20
mohan
  • 1
  • 2

1 Answers1

2

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.

NazaRN
  • 399
  • 1
  • 5
  • Thanks for answering, I have chosen to do option B, I have share code [here](https://codeshare.io/4ekO3d), but list it not empty then validation is not passed in that case can you tell me, How should I get those error messages and I am getting only one message in the list as, each one is enclosed in **if** – mohan Feb 16 '22 at 06:08