How can i get the error number instead of error message in an Exception in C#? [duplicate]

时光总嘲笑我的痴心妄想 提交于 2019-12-05 17:02:12

If you're looking for the win32 error code, that's available on the Win32Exception class

catch (Win32Exception e)
{  
    Console.WriteLine("ErrorCode: {0}", e.ErrorCode);
}

For plain old CLR exception, there is no integer error code.

Given the problem you describe, I'd go with millimoose's solution for getting resource strings for each type of exception.

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.)

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:

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.


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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!