Wim Ombelets
Wim Ombelets

Reputation: 5265

Localization of Exception Message inside class files?

If a class file contains some initial validation and throws an Exception in the case where validation fails,

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

Answers (1)

volpav
volpav

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

Related Questions