我从最新的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
?
谢谢。我阅读了一些更多的文章,并使其与您的代码示例相似,但是我返回了该服务中具有错误的实体。只要返回,如果它有错误,作为一个布尔值是一个好主意,并且在许多情况下肯定就足够了。 – 2012-03-18 22:44:03
随时接受这个答案。 ;) – Gregg 2012-03-20 13:17:47
的确,我正在等待一些更多的意见,但在我看来,你是SO上唯一的Grails专家。 ;) – 2012-03-20 14:29:59