@doelleri 提到了渲染状态代码可以做什么。
下面显示了一种可以在控制器中实现 DRYness 的“不那么时髦”的方式。但同样,如果您想将 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)
另请注意,当您处理已检查的异常时,事务不会在服务层中回滚。还有其他事情要做,我认为这超出了这个问题的范围。