【问题标题】:groovy: how to catch exceptions on AsyncHttpBuildergroovy:如何在 AsyncHttpBuilder 上捕获异常
【发布时间】:2014-04-24 17:24:12
【问题描述】:

我正在尝试对域进行异步调用。如果我使用 json 响应指定一个有效地址,则以下代码运行良好,但是当地址无效时,我希望能够捕获任何可能的异常。

如何捕获返回的异常?

这里是堆栈跟踪的摘录:

消息:无效的 JSON 字符串

...

http.AsyncHTTPBuilder - 响应委托引发的异常: groovyx.net.http.HTTPBuilder$RequestConfigDelegate@420db81e

代码如下:

def http = new AsyncHTTPBuilder( poolSize : 1,
                                 contentType : ContentType.JSON )

def futureResult

futureResult = http.request( "http://www.notexistingdomainxyzwq.com/",
                             Method.GET,
                             ContentType.JSON ) {
    response.success = { resp, json ->
        log.info("SUCCESS")             
    }

    response.failure = { resp, json ->
        log.info("ERROR")
    }

}

log.info("Call started");

try {
    while (!futureResult.done) {
        log.info('waiting...')
        log.info("DONE: ${futureResult.done}")
        Thread.sleep(1000)
    }
} catch(ex) {
    log.error("EXCE ${ex}")
}

log.info("Call completed")

【问题讨论】:

    标签: json asynchronous groovy httpbuilder


    【解决方案1】:

    如果你调用futureResult.get()来阻塞并等待结果,这将抛出你可以捕获的异常:

    try {
        def result = futureResult.get()
        log.info( "Done: $result" )
    } catch(ex) {
        log.error("EXCE ${ex}")
    }
    

    【讨论】:

      猜你喜欢
      • 2013-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-18
      • 2015-03-16
      • 2017-03-14
      • 2016-12-15
      相关资源
      最近更新 更多