我有一个相当简单的Grails控制器操作,它将参数绑定到域实例并将其传递给处理持久性的服务。
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块中的return语句是一种不好的做法。你还怎么实现错误处理?
答案 0 :(得分:3)
您在捕获阻止中没有做任何重要的事情。 codenarc会对此做些什么(移动返回尝试阻止):
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])
}
P.S。谢谢你的链接。从未听说过codenarc。
答案 1 :(得分:2)
+1 @Mr。猫。像。的东西。
def finishBooking() {
Booking booking = new Booking(params)
try {
booking = bookingService.saveBooking(booking)
if (booking.hasErrors()) {
flash.message = "Reservation failed. Check the required fields."
render(view: "index", model: [booking: booking])
}
} catch (ReservationException e) {
log.error("Error saving booking", e)
flash.message = "Couldn't save the reservation."
render(view: "index", model: [booking: booking])
}
[booking: booking]
}