英文的异常信息? [英] Exception messages in English?

查看:21
本文介绍了英文的异常信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们通过将 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?

推荐答案

这个问题可以部分解决.框架异常代码根据当前线程区域设置从其资源加载错误消息.在某些异常情况下,这会在访问 Message 属性时发生.

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
  }
}

但是,正如 Joe 在对此回复的较早修订版的评论中正确指出的那样,有些消息已经(部分)在抛出异常时从语言资源加载.

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("foo") 异常时生成的消息的参数不能为空"部分.在这些情况下,即使使用上述代码,消息仍会(部分)本地化.

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 代码,开始时使用 en-US 语言环境,对此您似乎无能为力:.NET Framework 异常代码没有用于覆盖错误消息区域设置的工具.

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.

这篇关于英文的异常信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆