@doelleri已經提到了可以爲渲染狀態代碼準確完成的工作。如下所示,您可以在控制器中實現DRYness的「不那麼groovier」方式。但是,如果您想將try catch塊移到實用程序中,您可以再實現一些功能。
//Custom Exception
class CustomException extends Exception{
Map errorMap
CustomeException(Map map, String message){
super(message)
this.errorMap = map
}
....
}
//service
def getSomethingGood(){
....
....
if(something bad happened){
throw new CustomException([status: HttpStatus.NOT_FOUND.value,
message: "Something really got messed up"],
"This is a custom Exception")
//or just return back from here with bad status code
//and least required data
}
......
return goodObj
}
def getSomething(){
def status = HttpStatus.OK.value
def message
try{
def obj = getSomethingGood()
message = "success value from obj"
//or can also be anything got from obj etc
} catch(CustomException c){
status = c.errorMap.status
message = c.errorMap.message
}
[status: status, message: message]
}
//controller
def obj = someService.getSomething()
render(status: obj.status, text: obj.message)
另請注意,處理選中的異常時,事務不會在服務層中回滾。還有其他事情要做,我認爲這超出了這個問題的範圍。
我不知道爲什麼你不想從控制器返回狀態代碼?我的意思是,自從我第一次開始使用Java/Groovy以來,我被教導說它是實現的正確方法(服務拋出異常,控制器捕獲並返回狀態碼)。服務不應該知道請求處理的任何內容,控制器也不知道任何有關業務邏輯的知識? –