Repetitive try-catch blocks with Groovy 'with' closure?

孤者浪人 提交于 2019-12-01 17:48:33
dmahapatro

You can simply do as below by using tryCatchClosure what you have now. You can even make tryCatchClosure a method which takes Closure as a parameter.

class WidgetService {
    WidgetDao widgetDao = new WidgetDao()

    def tryCatchClosure(Closure closure) {
        try {
            closure()
        } catch(WidgetException wexc) {
            log.error(wexc)
            int x = doFizz()
            long y = doBuzz(x)
            determineHowToHandle(y)
        }
    }

    createWidget(String name, int type) {
        tryCatchClosure {
            widgetDao.createWidget(name, type)
        } 
    }

    Widget getWidgetById(Long id) {
        tryCatchClosure {
            widgetDao.getWidgetById(id)
        }
    }

    Widget getWidgetByName(String name) {
        tryCatchClosure {
            widgetDao.getWidgetByName(name)
        }
    }

    def deleteWidget(Widget w) {
        tryCatchClosure {
            widgetDao.deleteWidget(w)
        }
    }

    // ...dozens of more methods with *exact* same catch block
}

Or you can also intercept each method call on WidgetDao by overriding invokeMethod method on its metaClass and handle exception (try/catch). Similar to this.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!