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

前端 未结 1 1842
隐瞒了意图╮
隐瞒了意图╮ 2021-01-18 22:50

I have the following Groovy class:

@Slf4j
class WidgetService {
    WidgetDao widgetDao = new WidgetDao()

    createWidget(String name, int type) {
                 


        
相关标签:
1条回答
  • 2021-01-18 23:43

    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.

    0 讨论(0)
提交回复
热议问题