2017-05-04 58 views
0

我在withTransaction方法的基礎上,當作者找不到時拋出一個自定義異常。但是我面對的問題是即使代碼在異常塊內部不存在,作者,它不存在於流程之外,而是繼續流動。 只是想檢查是否有任何我在這裏失蹤或做錯了。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() 
} 

感謝 山姆

+0

因此,「作者未找到」寫入您的日誌,但它仍嘗試設置空對象的狀態?你的代碼看起來很好。 – Ivar

+0

是的,它仍在繼續處理下一組代碼,它是'author.status ='completed',author.save()'。 – Sam

+0

所以,爲了100%確定,您會在日誌中看到「作者未找到」,並且會拋出NullPointerException,因爲它無法設置狀態?如果是這種情況,你應該嘗試清理項目並重建它。 – Ivar

回答

0

你真的有authStatus -> def author = Author.get(id)都在同一行?或者​​在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') 
} 

個人而言,我可能會換整個事情四處嘗試捕捉,甚至沒有拋出具體案例,而是試圖捕捉獲取和保存由於您可能獲得了記錄,但是您是否設法正確保存了錯誤?

+0

沒有理由說明爲什麼這段代碼應該與問題中的代碼不同。它的可讀性和清潔度都很低,如果你沒有將作者的特殊狀態應該在if語句中處理,而不是在「正常」流程中進行處理 –

+0

@TomasBartalos不會質疑這一點,我的觀點是真的要嘗試它從各個角度來看看行爲是否存在差異。這就是問題在SO成爲問題之前如何被消除。從各個角度嘗試並理解行爲。 – Vahid