'What is the best way to implement error code either by Enum or Constant
I need to handle error codes for the project. Previously, the enums were implemented like the following
enum ErrorCode{
None=0,
InvalidUserName = 1,
InvalidEmail
}
Later, we thought to move to some user defined error code like the following.
"ERR001", "ERR001" .. etc.
For that, I have two options,
- Using string annotation for the enum
- Using constants or readonly static.
What is the best way to do either by enum (which does not support string) or constant?
Solution 1:[1]
Assign a numerical value to your error reason enum and prefix it with ERR.
public enum Error
{
None = 0,
Duplicate = 1,
MissingDetails = 2,
MissingFocus = 3,
NoSampleCode = 4
}
public static string GetErrorCode(Error error)
{
return $"ERR{(int)error:D3}";
}
Console.WriteLine(GetErrorCode(Error.NoSampleCode)); // prints "ERR004"
If this isn't what you require, you need to provide more information / sample code in your question so we can understand what is needed.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ray |
