我有一个相当简单的 Grails Controller 操作,它将参数绑定(bind)到域实例并将其传递给处理持久性的服务。
def finishBooking() {
Booking booking = new Booking(params)
try {
booking = bookingService.saveBooking(booking)
} catch (ReservationException e) {
log.error("Error saving booking", e)
flash.message = "Couldn't save the reservation."
render(view: "index", model: [booking: booking])
return
}
if (booking.hasErrors()) {
flash.message = "Reservation failed. Check the required fields."
render(view: "index", model: [booking: booking])
} else {
[booking: booking]
}
}
根据codenarc ,catch block 中的 return 语句是一种不好的做法。您将如何实现错误处理?
最佳答案
你没有做任何重要的事情捕获 堵塞。 codenarc 会对此说些什么(将 return 移至 try block ):
def finishBooking() {
Booking booking = new Booking(params)
try {
booking = bookingService.saveBooking(booking)
if (!booking.hasErrors()) {
return [booking: booking]
} else {
flash.message = "Reservation failed. Check the required fields."
}
} catch (ReservationException e) {
log.error("Error saving booking", e)
flash.message = "Couldn't save the reservation."
}
render(view: "index", model: [booking: booking])
}
附言感谢您的链接。从未听说过codenarc。
关于grails - 如何避免从 catch block 返回 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16717843/