Grails - 内部异常withTransaction块无法正常工作

时间:2017-05-04 11:13:31

标签: grails

当找不到作者时,我在withTransaction方法中抛出了一个自定义异常。但是我面临的问题是,即使代码在异常块内为不存在的作者而存在,它也不存在于流动但继续流动。 只是想检查一下我在这里缺少什么或做错了。

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()
}

由于 萨姆

1 个答案:

答案 0 :(得分:0)

你真的有authStatus -> def author = Author.get(id)一行吗?或authStatus ->withTransaction,通常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') 
}

就我个人而言,我可能会把整个事情包裹在try catch中,甚至不抛出那个特定的情况,而是尝试捕获get并保存错误,在try catch的底部抛出一个,因为你可能已经获得了记录但是你设法保存了它正确吗?