I have the following Groovy class:
@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 }
As you can see, I have a lot of duplicates, template code in try-catch blocks. It would be nice if I could define a closure or some kind of AOP-based handler, just pass the widgetDao method of interest to the closure / handler like lambda or something like that:
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) } }
So my "WidgetService" might look something like this:
@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 }
Is it possible? If so, how?
smeeb source share