Reputation: 973
I would like to pass multiple error messages to the GUI. How do I have to do this? Please have a short look at my abstract example above:
try
{
LogIn(usr, pwd); //entry point
}
catch(Exception ex)
{
throw new Exception("Login failed.");
}
public void LogIn(string usr, string pwd) {
if(usr == "") {
throw new Exception("Username was empty.");
}
if(pwd== "") {
throw new Exception("Password was empty.");
}
try
{
//do some other stuff without a more specific error message
}
catch
{
throw;
}
}
Later I would like to get a result error message like
Login failed. Password was empty.
if the user didn't type in a password. Right now I just get the last error message ("login failed.") on top and so just half of my information that I would like to give to the user.
Upvotes: 0
Views: 1392
Reputation: 5150
I would rethink your structure. As in the comments pointed out there are some things to consider:
List<string>
for collecting issues:public void LogIn(string usr, string pwd)
{
List<string> errors = new List<string>();
if(string.IsNullOrEmpty(usr))
{
errors.Add("Username is empty.");
}
if(string.IsNullOrEmpty(pwd))
{
errors.Add("Password is empty.");
}
if(errors.Count > 0) // If errors occur, throw exception.
{
throw new Exception(string.Join("\r\n",errors));
}
}
Upvotes: 2
Reputation: 239684
You can nest exceptions:
try
{
LogIn(usr, pwd); //entry point
}
catch(Exception ex)
{
throw new Exception("Login failed.", ex);
}
Note the second argument, and the InnerException
property of Exception
.
But before doing do, consider whether the above block is adding any value. If you just let the Password was empty
exception escape instead, the caller would still know, generically, that the login has failed, and that exception alone seems to contain all the required information.
Only catch
an exception if you have something useful to do - if you can recover an error condition, add information or do not want to expose implementation details to your callers. Otherwise, let the exceptions rise to a level where something useful can be done.
Upvotes: 4
Reputation: 324
You could just use ex.Message
which would either be Password was empty. or Username was empty.
Upvotes: 0