Reputation: 5265
If a class file contains some initial validation and throws an Exception
in the case where validation fails,
is it considered good practice to enable localization inside the class files for the Exception Message
?
How would I catch these localized exceptions? Simple string comparison of the Exception Message
seems... not elegant to say the least. Are there preferred and proven better ways to approach this?
an example of how I was planning this:
private ResourceManager localization;
private string email;
public string Email
{
get { return email; }
set
{
if (value.Length > 50)
throw new ArgumentException(localization.GetString("toolong_email"));
else if (!IsValidEmail(value))
throw new ArgumentException(localization.GetString("invalid_email"));
else
email = value;
}
}
Microsoft's Best Practices for Handling Exceptions states: "Include a localized description string in every exception."
I've tagged this C# but in the end this is more about general practices, I suppose. I was thinking that this might be more of a programmers.stackexchange question but decided to post it here. Unsure.
Upvotes: 0
Views: 2120
Reputation: 5128
You could follow a System.Net.WebException
design and pass an error type (like it's done with the Status
property of the mentioned exception class) that is easy to work with from code. The exception message itself can be localized (like any other CLR exceptions that use resources rather than hardcoded strings, as far as I remember).
Another solution would be to throw different exceptions for different types of errors:
if (value.Length > 50)
{
throw new ValueLengthExceededException("Email",
localization.GetString("toolong_email"));
}
else if (!IsValidEmail(value))
{
/*
Or a generic "InvalidFormatException/FormatException" with
member name like a previous example.
*/
throw new InvalidEmailException(localization.GetString("invalid_email"));
}
Hope this helps.
Upvotes: 1