如何在 C# 中的异常中获取错误号而不是错误消息?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15462675/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can i get the error number instead of error message in an Exception in C#?
提问by Rika
Is there a way that i can get the corresponding error code of an Exceptions
?
I need the thrown exceptions error code instead of its message , so that i based on the error code i show the right message to the user.
有没有办法可以得到一个对应的错误代码Exceptions
?我需要抛出的异常错误代码而不是它的消息,以便我根据错误代码向用户显示正确的消息。
采纳答案by p.s.w.g
If you're looking for the win32 error code, that's available on the Win32Exception
class
如果您正在寻找 win32 错误代码,可在Win32Exception
类中找到
catch (Win32Exception e)
{
Console.WriteLine("ErrorCode: {0}", e.ErrorCode);
}
For plain old CLR exception, there is no integer error code.
对于普通的旧 CLR 异常,没有整数错误代码。
Given the problem you describe, I'd go with millimoose's solution for getting resource strings for each type of exception.
考虑到您描述的问题,我会使用milloose的解决方案来获取每种异常类型的资源字符串。
回答by millimoose
The whole point of exceptions is that they provide richer information than just an error code. By default, they don't have one, and don't really need one. If you like using error codes you can just use your own exception base class that you derive all your exceptions from:
异常的全部意义在于它们提供了比错误代码更丰富的信息。默认情况下,他们没有一个,也不需要一个。如果您喜欢使用错误代码,您可以使用您自己的异常基类,您可以从中派生出所有异常:
public abstract class MyExceptionBase : Exception
{
public int ErrorCode { get; set; }
// ...
}
That said, I wouldn't bother. Personally I map exceptions to error messages using their type name:
就是说,我不会打扰。我个人使用它们的类型名称将异常映射到错误消息:
ResourceManager errorMessages = ...;
errorMessages.GetString(ex.GetType().FullName);
(You can also create more flexible schemes, like make the resources format strings and interpolate exception properties into them.)
(您还可以创建更灵活的方案,例如使资源格式化字符串并将异常属性插入其中。)
回答by Andrew Moore
For a COM exception that is upgraded to a Managed exception, you will be able to retrieve the "error code"from the HResult
property as such:
对于升级为托管异常的 COM 异常,您将能够从属性中检索“错误代码”,HResult
如下所示:
try {
// code goes here
} catch(System.IO.FileNotFoundException ex) {
Console.WriteLine(
String.Format("(HRESULT:0x{1:X8}) {0}",
ex.Message,
ex.HResult)
);
}
Not all exceptions however will have a meaningful HResult set however.
然而,并非所有异常都会有一个有意义的 HResult 集。
For .NET 3.0, 3.5 and 4.0 you will have to use reflection to get the value of the HResult
property as it is marked protected
.
对于 .NET 3.0、3.5 和 4.0,您必须使用反射来获取HResult
标记为 的属性值protected
。