【问题标题】:How to avoid returning null from a catch block?如何避免从 catch 块返回 null?
【发布时间】:2013-05-23 15:22:14
【问题描述】:

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

【问题讨论】:

  • 你不需要 return 在 catch 中。您已经在渲染视图了。
  • 如何放置所有代码来尝试阻止并从catch中删除返回?
  • @Mr.Cat 不是故意踩你的脚趾的……你有所有的功劳。 :)
  • @dmahapatro 没关系 (=

标签: grails codenarc


【解决方案1】:

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

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

【讨论】:

  • 事实上我们有一个codenarc 的插件。它已经很棒了。 :)
【解决方案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]
}

【讨论】:

    猜你喜欢
    • 2012-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-15
    • 2016-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多