grails - 如何避免从 catch block 返回 null?

标签 grails codenarc

我有一个相当简单的 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/

相关文章:

grails - Grails 2.4.4-将i18n设置为引用与/grails-app/i18n不同的目录

hibernate - 从grails服务中插入数据库失败

gradle - 在 Gradle 中使用 CodeNarc 生成多种报告类型

grails - 如何使用Codenarc插件创建自定义规则集?

exception - Groovy Codenarc.xml org.xml.sax.SAXParseException xsi :schemaLocation not associated with element type ruleset not bound

Grails 异步执行多个原生 sql 查询

grails - 使用 "Getting Started with Grails"电子书进行集成测试时出现编译错误

grails - Grails表单重定向/渲染的最佳实践

gradle - 如何使用不同的规则集为主类和测试类生成 Codenarc 报告?

java - 永远不应在非静态导入之后的静态导入语句