Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 303
Hossein Avatar asked Dec 05 '22 12:12

Hossein


2 Answers

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.

like image 65
p.s.w.g Avatar answered Mar 15 '23 22:03

p.s.w.g


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

like image 44
millimoose Avatar answered Mar 15 '23 22:03

millimoose