C# - 英语异常消息?英语、异常、消息

2023-09-02 10:17:16 作者:一切免谈

我们正在记录的发生在我们的系统中通过写Exception.Message到文件中的任何异常。然而,都写在客户端的培养。和土耳其的错误并不意味着对我很重要。

We are logging any exceptions that happen in our system by writing the Exception.Message to a file. However, they are written in the culture of the client. And Turkish errors don't mean a lot to me.

那么,如何能在不改变用户的文化登录英文任何错误消息?

So how can we log any error messages in English without changing the users culture?

推荐答案

这个问题可以部分合作周围。该框架例外code,从资源加载错误消息,基于当前线程区域。在一些例外的情况下,这种情况发生在消息属性被访问的时间。

This issue can be partially worked around. The Framework exception code loads the error messages from its resources, based on the current thread locale. In the case of some exceptions, this happens at the time the Message property is accessed.

对于那些异常,您可以通过快速切换线程区域设置为en-US,而记录日志(先保存原来的用户区域,之后立即恢复吧)得到消息的完整美国英语版本。

For those exceptions, you can obtain the full US English version of the message by briefly switching the thread locale to en-US while logging it (saving the original user locale beforehand and restoring it immediately afterwards).

在一个单独的线程这样做就更好了:这可以确保不会有任何副作用。例如:

Doing this on a separate thread is even better: this ensures there won't be any side effects. For example:

try
{
  System.IO.StreamReader sr=new System.IO.StreamReader(@"c:does-not-exist");
}
catch(Exception ex)
{
  Console.WriteLine(ex.ToString()); //Will display localized message
  ExceptionLogger el = new ExceptionLogger(ex);
  System.Threading.Thread t = new System.Threading.Thread(el.DoLog);
  t.CurrentUICulture = new System.Globalization.CultureInfo("en-US");
  t.Start();
}

凡ExceptionLogger类看起来是这样的:

Where the ExceptionLogger class looks something like:

class ExceptionLogger
{
  Exception _ex;

  public ExceptionLogger(Exception ex)
  {
    _ex = ex;
  }

  public void DoLog()
  {
    Console.WriteLine(_ex.ToString()); //Will display en-US message
  }
}

然而,随着乔正确地指出了这个答复的早期版本的意见,一些消息已经(部分),装在语言资源异常被抛出的时候。

However, as Joe correctly points out in a comment on an earlier revision of this reply, some messages are already (partially) loaded from the language resources at the time the exception is thrown.

这适用于参数不能为空当一个ArgumentNullException(富)抛出异常,例如生成的消息的一部分。在这些情况下,仍然会出现消息(部分)的局部,使用上述code时也​​是如此。

This applies to the 'parameter cannot be null' part of the message generated when an ArgumentNullException("foo") exception is thrown, for example. In those cases, the message will still appear (partially) localized, even when using the above code.

除了用不切实际的黑客,比如在一个线程中运行所有非UI code与EN-US区域,首先,似乎没有要多少你可以做的是:。 NET Framework异常code没有设施覆盖的错误消息的语言环境。

Other than by using impractical hacks, such as running all your non-UI code on a thread with en-US locale to begin with, there doesn't seem to be much you can do about that: the .NET Framework exception code has no facilities for overriding the error message locale.