定义错误代码
是否有定义错误代码的“正确方法”?我的意思是,我不久前构建了一个引发自定义异常的库,但我将自定义错误消息定位到开发人员的角度。现在我正在总结 GUI,当我捕获这些异常时,我需要更多用户友好的消息。这本身不是问题,但可以说,我有 ReceiverNotAvailableException 异常和 NoMessageReceivedException。对于我来说,作为一名开发人员,它们意味着完全不同的事物并且具有不同的内部消息,但对于最终用户来说,它们只是意味着“找不到用户”。我想显示类似“用户未找到(错误 X)”的内容,其中 X 根据引发的异常而变化 - 如果你问我,这很常见。
我的问题是:我应该根据哪种异常选择 X=1、2 等等,还是应该出于某种原因选择更复杂的东西?我知道这听起来像是一个愚蠢的问题,但我真的很想知道这种情况下的“最佳实践”(我不太喜欢这个词)是什么。
顺便说一句,当然,我有一个表将每个代码映射到其相应的异常,无论哪种情况。
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 my 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您的异常不能重叠,那么使用 HashTable[ExceptionName] = "Error Message" 看起来是一个明智的选择。如果可以的话,您可以使用如下所示的内容:
定义可以重叠(即同时发生)的消息代码的标准方法是使用 2 的幂:
等等。然后,在代码中您可以执行
最后,在接收端您可以:
解释:
然后
,在检查代码上
现在,如果您使用异常,您可以使用相同的方法,只要发生异常,就会冒泡错误代码。虽然这种习惯用法在 C 中更常见。
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:
and so on. Then, in code you can do
Finally, on the receiving end you can:
Explanation:
Then
and, on the checking code
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.