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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.