我需要显示每个在适当的位置服务获得了一些验证消息,我解决它把消息中的异常:可以在异常中存储其他对象吗?
class InvalidInputException extends RuntimeException {
def errors
InvalidInputException(String s) {
super(s)
}
InvalidInputException(String s, errors) {
super(s)
this.errors = errors
}
}
这样的话,我可能会抛出异常发送错误:
if (errors) {
throw new InvalidInputException("There were some errors", errors)
}
..然后我在控制器处理错误后,经过捕获异常:
...
catch (InvalidInputException e) {
if (e.errors) {
// set them up to display appropriately
}
// render the view
}
现在,我读过Groovy的例外可能花费太多,所以...这太糟糕了吗? 在异常中可能会遇到什么问题?
这比处理返回的错误消息要容易得多,而且代码要短得多。
看起来对我来说......您在哪里阅读过_“Groovy的例外可能花费太多”_?另外,你对“太多”的定义是什么? –
一个例外花费太多的想法对我来说似乎很奇怪。例外是例外。如果你处于抛出异常(它们是昂贵的,也是普通的java)对你的性能有影响的地步,要么你真的做得非常糟糕(抛出太多例外),要么你做得很好,你可能负担得起重新设计以解决问题。 – loteq
@tim_yates我认为OP想要说出loteq对昂贵的说法。例如,这里讨论[这里](http://stackoverflow.com/questions/299068/how-slow-are-java-exceptions)。 –