我正在基于未找到作者时根据方案在使用转移方法的情况下扔一个自定义。作者,它不是从流中存在的,而是继续流动。只是想检查一下我在这里缺少的东西还是做错了。
Author.withTransaction() {
authStatus -> def author = Author.get(id)
if (!author) {
log.warn "author not found"
throw new NotFoundException('author not found')
}
author.status = 'completed'
author.save()
}
谢谢sam
您真的在一行上都有authStatus -> def author = Author.get(id)
吗?或withTransaction
线上的authStatus ->
,通常return
可以阻止某些内容继续进行,但是由于您投掷,因此不需要。为什么不扭转逻辑为
if (author) {
do something
return
}
//obviously we didn't have an author since we haven't returned so back to your throw
log.warn "author not found"
throw new NotFoundException('author not found')
我会将其更改为
Author.withTransaction {
def author = Author.get(id)
if (author) {
author.status = 'completed'
author.save()
return author
}
log.warn "author not found"
throw new NotFoundException('author not found')
}
就我个人而言,我可能会围绕着捕获的整个事情,甚至不会丢弃特定的情况,而是尝试捕获并保存错误,因为您可能已经有了记录,但您是否设法保存它正确吗?