How to handle translation of exception message?

2020-08-23 01:22发布

问题:

I don't really know the best way to handle exception in an multi-language application.

Where should I handle the translation of the error message (Exception.Message)?

Shall I translate the message in the ctor as soon as I throw the exception?

throw new MyException("Error message", Resource.MyException_TranslatedMessage);

Or do I throw the exception and I use a home made helper that will find the error message using the type of the exception in the logic of the View?

try
{
    //...
}
catch(Exception ex)
{
    myLabel.Text = new ExceptionTranslator(ex).Translate();
}

Or, does Microsoft offer a tool or a mechanism to do that?

In a word: what are the good practices to handle exception messages translation?

回答1:

Most exceptions are there for technical purposes, unless your operations and maintenance crew are also located in different countries, those exceptions should simply have messages in the language of the people who write and maintain the application.

The .NET framework contains localized exception messages. For me as a developer, that's very annoying, since the exception messages in my local language (Dutch) don't mean as much as the original English exception messages. However, it seems reasonable for Microsoft to localize those framework exception messages, since their target audience can be located anywhere.

Some types of exceptions however, are explicitly thrown to be displayed to the user. These are your ValidationException or BusinessLayerException. Their clear contract is to be displayed to the user. Of course you should localize those exception messages, but instead of translating them, it's often much better and easier to pull the exception message from a localized resource when throwing the exception:

throw new ValidationException(Resources.InvalidUserName);


回答2:

Much better to only translate it when it needs to be displayed, IMHO. This applies to any localisable string, not just error messages.

Ideally, the logic of the code shouldn't care about the content - or language - of the message, it's only interested in the type of the exception. It's only the presentation layer that (might) need to display it in the local language.



回答3:

The external code should not translate messages

throw new MyException("Error message", Resource.MyException_TranslatedMessage);

This is best solution in my mind



标签: c# exception