groovy:如何捕获AsyncHttpBuilder上的异常

时间:2014-04-24 08:25:42

标签: json asynchronous groovy httpbuilder

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

如何捕获返回的异常?

这是stacktrace的摘录:

  

消息:无效的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")

1 个答案:

答案 0 :(得分:0)

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

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