【发布时间】:2012-03-19 06:07:53
【问题描述】:
我从最新的 Java 开发中了解到,抛出 RuntimeException 并以面向方面的方式处理它是服务层错误处理的当前趋势。这意味着,如果出现任何问题,您只需抛出 RuntimeException 或者更好,让 Bean Validation 发挥作用。
优点是:你不会用try-catch 和if(entity.getName() == nil) 检查阻塞你的代码。一切都在后台检查,使您的代码更具可读性。
所以我想知道,这将如何在 Grails 中完成?当然,如果我使用.save(failOnError:true),我会得到一个不错的ValidationException。但这会导致一个非常令人不快的默认错误页面,根本不会提高 Web 应用程序的可用性。
我还需要将它放在控制器级别的try-catch 块中吗?假设EntityService 有一个方法,如下所示:
def toggleSomething(String entityId) = {
if(!someOtherPrerequisite) {
throw new EntityException("SomeOtherPrerequisite was not satisfied") // extends RuntimeException
}
Entity entity = Entity.get(entityId)
entity.someProperty = somePropertyValue
entity.save(failOnError:true) // throws a ValidationException
}
然后控制器会这样调用它:
def toggle = {
try {
entityService.toggleSomething(params.id)
}
catch(e) {
flashHelper.error 'I'm sorry, something went wrong.'
}
}
但是当 Grails 在很多方面都是新的学校时,这似乎是相当老派的。难道没有办法更好地处理RuntimeExceptions 而不用try-catch 阻塞代码吗?
【问题讨论】:
标签: validation grails grails-2.0