动态异常消息是个好主意吗?
我正在为一个项目设计一个基础设施,我一直想知道使用参数格式化异常消息并使其动态化是否是一个好主意。
一方面,这意味着异常消息可能非常冗长。
在我看来,更严重的缺点是你不能期待某些消息。这些可以在异常处理、测试消息是这样还是那样以及在日志记录中使用(尽管这不是最佳实践)。但更令人不安的是,如果你打算在某个地方显示该消息(我就是这么做的),那么本地化就会变得更加困难。
所以我的问题是你对此有何看法,以及你是否有一个妥协的解决方案,让我既冗长(如果我记录异常)又保持一致性。
谢谢。
I'm designing an infrastructure for a project and I've been wondering if it'd be a good idea to format the exception's message with parameters, making it dynamic.
This means, on the one hand, that exception messages can be really verbose.
The downside, which is a lot stronger, in my opinion, is that you can't expect certain messages. These can be used (though it's not a best-practice) in exception handling, testing whether the message is this or that and in logging. But what's even more disturbing is that it will make localization a lot harder if you intent on showing that message somewhere (which I do).
So my question is what's your take on it and whether you have a compromising solution, giving me both verbosity (in case I log the exception) and consistency.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我相信在异常中包含参数通常非常有帮助。想想其他开发人员(以及您自己)会阅读该消息并尝试查找错误。或者更糟糕的是:用户可能会向您阅读异常消息或将其发布在论坛上,而您必须远程找出问题所在。
测试异常中的某些消息确实不是最佳实践。我认为这是不好的做法。我所知道的所有语言都允许您定义我们自己的异常类,并且如果纯类名称对您来说不够好(尽管通常是这样),还可以向该类添加自定义属性。我相信异常中的消息应该尽可能易于人类阅读,并且不需要通过代码来预测它们。
当然,你可以做得太过分。异常消息不应仅仅因为您想在其中包含所有可能的变量而变得太大/太长。明智地选择;-)。
I believe that including parameters in Exceptions is often extremely helpful. Think about that other developers (and you yourself) will read the message and try to find a bug. Or even worse: A user may read an exception message to you or post it on a forum and you have to find out what's wrong remotely.
Testing for certain messages in exceptions is indeed not best practice. I'd call it bad practice. All languages I know allow you to define our own Exception classes and also add custom properties to the class if the pure class name is not good enough for you (though it usually is). I believe messages in Exceptions should be as human readable as possible and there is no need for them to be predictable by code.
Of course you can overdo anything. Exception messages should not grow too large/long just because you wanted to include all possible variables in it. Select wisely ;-).