1

我有一个相当简单的 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 语句是一种不好的做法。您将如何实现错误处理?

4

2 回答 2

3

你在catch块中没有做任何重要的事情。codenarc 会对此说些什么(将 return 移至 try 块):

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])
}

PS 感谢您的链接。从未听说过codenarc。

于 2013-05-23T15:43:18.820 回答
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]
}
于 2013-05-23T15:29:57.973 回答