Reputation:
I want to create a bunch of errors. each specific to its own class and module. Then i would like to attach the id to an exception so when my msg change the id is still the same. How do i create this list of errors without maintaining a large global enum ?
Upvotes: 3
Views: 2303
Reputation: 161821
It's a naive idea that every possible "error" can be assigned a point in "error space". Consider a simple example, where a method throws a particular error (I'll be courteous and say "throws", though in context, it used to be "returns"):
public void MyMethod() {
// ...
throw new ErrorException(ErrorCodes.MyMethodError1); // Or something
}
Perhaps this method is only called from one place in Release 1. That means it's possible in that release to document that error code MyMethodError1 means a particular thing.
In the next release, the method is found to be useful, so it's called from three places. In fact, it's called from two different code paths in one of the places. Does MyMethodError1 mean the same thing now as it used to? I say that it doesn't.
Only by taking into account the circumstances of the calls, as determined by the call stack, can you determine the meaning of the particular exception. An error code does not help with that.
Upvotes: 0
Reputation: 96870
What's the purpose of having a unique identifier for each error? Any exception that your code throws already has information that uniquely identifies it, i.e. the type of exception and the module name and line of code that threw it. You don't need to assign an ID to an exception to know that it's not the same exception as one with a different type, or module, or line.
Generally speaking, the need to assign a unique ID to an entity emanates from the need to keep other information about that entity in some kind of durable store. What are the characteristics of that durable store? Those requirements almost certainly are going to provide the basis for evaluating the fitness of any particular ID scheme you come up with. What are they?
Upvotes: 1
Reputation: 116724
Divide the unsigned 32-bit hexadecimal number range up as a hierarchy:
0xMMCCCEEE
where:
Then you can have 0 to 0xFF (256) modules, and 0 to 0xFFF (4096) each of classes and errors, and you only have to ensure that each error is unique to its class, and each class is unique to its module, so you don't have to keep all error messages in a single giant table.
Example:
0x0401D00A
That's module 04, class 01D, error 00A.
Upvotes: 11