I have the following Groovy class:
@Slf4j
class WidgetService {
WidgetDao widgetDao = new WidgetDao()
createWidget(String name, int type) {
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.