c# - 从异常实例化或本地化异常消息中排除 FxCop DoNotPassLiteralsAsLocalizedParameters 违规

标签 c#

我在下面的方法代码中发现两条异常抛出行都违反了 DoNotPassLiteralsAsLocalizedParameters FxCop:

public bool IsPageAccessible(string url, string documentId) {
    if (url == null) {
        throw new ArgumentNullException("url", @"url must not be null, use string.Empty if you don't care what the url is.");
    }

    if (documentId == null) {
        throw new ArgumentNullException("documentId", "documentId must not be null, use string.Empty if you don't care what the documentId is.");
    }
    return true;
}

意思是:

fxcop Globalization#CA1303 String literals that are embedded in source code are difficult to localize. Avoid passing string literals as arguments in circumstances where a localized string is generally expected. Most localized applications, for example, should localize string arguments that are passed to exception constructors. When creating an Exception instance, therefore, a string argument retrieved from a string table is more appropriate than a string literal.

推理:

我不想本地化异常消息。只有英语很好。尽管我们正在构建 API,但所有开发人员都知道英语。无论如何,不​​应向生产服务器上的访问者显示异常消息。

问题:

  • 你不同意我关于异常消息本地化的推理吗?为什么?
  • 有没有办法只从所有异常实例化中排除这个 FxCop 警告?我们确实本地化了 API 的其他部分。最终用户可以看到文本的那些部分。因此,在这些情况下,我们可以通过保留警告来获得值(value)。
  • 你认为我应该如何处理这件事?

最佳答案

我认为你的推理很好,当我在 Visual Studio 中本地化异常并且找不到帮助时我讨厌它,因为编程的通用语言是英语。

更一般地说,你不应该试图遵守每一个 fxcop 规则,这很快就会成为一种负担。最好专注于规则的子集。

我认为您不能排除特定异常中的警告,但您可以使用 SuppressMessage 属性排除检测:

[SuppressMessage("Microsoft.Globalization", 
                 "CA1303:DoNotPassLiteralsAsLocalizedParameters", 
                 Justification="Exception are not localized")]
public bool IsPageAccessible(string url, string documentId) {
  if (url == null) {
    throw new ArgumentNullException("url", @"url must not be null, use string.Empty if you don't care what the url is.");
  }

  if (documentId == null) {
    throw new ArgumentNullException("documentId", "documentId must not be null, use string.Empty if you don't care what the documentId is.");
  }
  return true;
}

另一种方法是写一个 custom fxcop rule添加此行为。

关于c# - 从异常实例化或本地化异常消息中排除 FxCop DoNotPassLiteralsAsLocalizedParameters 违规,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3619296/

相关文章:

c# - 在 cshtml 页面内异步加载

c# - LINQ to XML 后代中的后代

c# - 如何从基于 OnMethodBoundaryAspect 的日志记录中排除?

c# - WPF ListBox 多项选择不会在模型上引发 SelectedItem

c# - 如何修复 "namespace x already contains a definition for x"错误?转换为VS2010后发生

c# - 'Freezer.Utils.ZipDeployer' 的类型初始值设定项抛出异常

c# - 如何使用 JsonConvert 反序列化此 JSON?

c# - 面向 C# 开发人员的 VB.NET

c# - 你如何找到调用者函数?

c# - 如何在应用程序的同一实例中打开关联文件