This question already has an answer here:
- How to get Exception Error Code in C# 5 answers
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.
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
.
来源:https://stackoverflow.com/questions/15462675/how-can-i-get-the-error-number-instead-of-error-message-in-an-exception-in-c