具有Groovy’with’闭包的重复try-catch块?
发布时间:2020-12-14 16:24:35 所属栏目:大数据 来源:网络整理
导读:我有以下Groovy类: @Slf4jclass WidgetService { WidgetDao widgetDao = new WidgetDao() createWidget(String name,int type) { try { widgetDao.createWidget(name,type) } catch(WidgetException wexc) { log.error(wexc) int x = doFizz() long y = doB
我有以下Groovy类:
@Slf4j class WidgetService { WidgetDao widgetDao = new WidgetDao() createWidget(String name,int type) { try { widgetDao.createWidget(name,type) } catch(WidgetException wexc) { log.error(wexc) int x = doFizz() long y = doBuzz(x) determineHowToHandle(y) } } Widget getWidgetById(Long id) { try { widgetDao.getWidgetById(id) } catch(WidgetException wexc) { log.error(wexc) int x = doFizz() long y = doBuzz(x) determineHowToHandle(y) } } Widget getWidgetByName(String name) { try { widgetDao.getWidgetByName(name) } catch(WidgetException wexc) { log.error(wexc) int x = doFizz() long y = doBuzz(x) determineHowToHandle(y) } } def deleteWidget(Widget w) { try { widgetDao.deleteWidget(w) } catch(WidgetException wexc) { log.error(wexc) int x = doFizz() long y = doBuzz(x) determineHowToHandle(y) } } ...dozens of more methods with *exact* same catch block } 正如您所看到的,我的try-catch块中有很多重复的样板代码.如果我可以定义一个闭包或某种基于AOP的处理程序,只需将widgetDao感兴趣的方法作为lambda或类似的东西传递给闭包/处理程序,那就太好了: def createWidgetClosure = { it => widgetDao.createWidget(it.name,it.type) } def getWidgetByIdClosure = { it => widgetDao.getWidgetById(it.id) } def tryCatchClosure = { closure => try { closure() } catch(WidgetException wexc) { log.error(wexc) int x = doFizz() long y = doBuzz(x) determineHowToHandle(y) } } 这样我的`WidgetService就可以看起来像这样: @Slf4j class WidgetService { WidgetDao widgetDao = new WidgetDao() createWidget(String name,int type) { tryCatchClosure(createWidgetClosure()) } Widget getWidgetById(Long id) { tryCatchClosure(getWidgetByIdClosure()) } ...dozens of more methods with *exact* same catch block } 这可能吗?如果是这样,怎么样? 解决方法
您可以使用tryCatchClosure,现在只需执行以下操作.你甚至可以让tryCatchClosure成为一个以Closure作为参数的方法.
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 } 或者您也可以通过覆盖其metaClass上的invokeMethod方法并处理异常(try / catch)来拦截WidgetDao上的每个方法调用. Similar to this. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |