开发者

Defining error codes

Is there a "right way" to define error codes? I mean, I've built a library a while ago that throws custom exceptions, but I targeted the custom error messages to a developer's standpoint. Now I'm wrapping up the GUI and when I catch those exceptions, I need more user friendly messages. That's not a problem in itself, but let's say, I have m开发者_如何学JAVAy ReceiverNotAvailableException exception and NoMessageReceivedException. To me, as a developer, they mean completely different things and have different inner messages, but to the end-user they just mean "User not found". I'd like to display something like "User not found (error X)" where X varies depending on which exception is raised - pretty commonplace if you ask me.

My question is: should I go with X=1, 2 and so forth depending on what kind of exception or should I opt for something more complicated for whatever reason? I know it sounds like a dumb question, but I'd really like to know what the "best practice" (I'm not so fond of the term) is in this case.

BTW, of course I'd have a table mapping each code to its corresponding exception, whichever the case is.


If your exceptions can't overlap, then going with a HashTable[ExceptionName] = "Error Message" looks like a sane option. If they can you can use something like the following:

The standard way to define message codes that can overlap (this is, occur at the same time) is to use powers of two:

define ERROR_SYSTEM_DOWN  1
define ERROR_DATABASE_UNREACHABLE 2
define ERROR_SPACE_UNAVAILABLE 4
define ERROR_DISK_DIED 8

and so on. Then, in code you can do

if (disk_died() && no_space()) {
    int errorCode = ERROR_DISK_DIED | ERROR_SPACE_UNAVAIABLE; //Binary or
    return errorCode;
}

Finally, on the receiving end you can:

if (errorCode & ERROR_DISK_DIED == ERROR_DISK_DIED) { //Binary and
    //then, at least, disk died. You can check for the rest in the same way
}

Explanation:

ERROR_SYSTEM_DOWN = 0001
ERROR_DATABASE_UNREACHABLE = 0010
ERROR_SPACE_UNAVAILABLE = 0100
ERROR_DISK_DIED = 1000

Then

1000 | 0100 = 1100

and, on the checking code

1100 & 0100 = 0100

Now, if you are using exceptions you can use the same approach, bubbling up the errorCode as long as exception occur. Although this idiom is more common in C.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜