我有一个非 Android Java 应用程序,一个接一个地上传数千个文件。
对于每个插入,我都像这样实现指数退避:
Random randomGenerator = new Random();
for(int i = 0; i < 5; i++) {
try {
return service.files().insert(body, mediaContent).execute();
} catch(GoogleJsonResponseException e) {
if (e.getDetails().getCode() == 500
|| e.getDetails().getCode() == 501
|| e.getDetails().getCode() == 502
|| e.getDetails().getCode() == 503
|| e.getDetails().getCode() == 504
|| e.getDetails().getCode() == 403) {
Thread.sleep((1 << i) * 1000
+ randomGenerator.nextInt(1001));
} else {
// error besides 5xx
throw e;
}
} catch (HttpResponseException e) {
if (e.getStatusCode() == 500 || e.getStatusCode() == 501
|| e.getStatusCode() == 502 || e.getStatusCode() == 503
|| e.getStatusCode() == 504
|| e.getStatusCode() == 403) {
Thread.sleep((1 << i) * 1000
+ randomGenerator.nextInt(1001));
} else {
// error besides 5xx
throw e;
}
} catch (SocketTimeoutException e) {
Thread.sleep((1 << i) * 1000 + randomGenerator.nextInt(1001));
}
问题是:
我的应用多次捕获 GoogleJsonResponseException,但 e.getDetails() 返回 null
因此我在检查错误代码时遇到空指针异常。
返回 Google JSON 错误详细信息或返回 null(例如,如果响应不是 JSON)。
基本上,我捕获了一个 GoogleJsonResponseException
但没有 JSON。
为什么我可以捕获 GoogleJsonResponseException
而实际上没有任何关联的 Json?为什么它不捕获 HttpResponseException
?
我希望我的应用能够在返回 Json 时捕获/使用它,但是当 GoogleJsonResponseException
甚至不能保证返回 Json 时,我不知道如何可靠地做到这一点。
有什么建议吗?
我是否应该只使用 HttpResponseException
来可靠地检查 statusCode,然后查看 getMessage()
以查看是否有 JSON?
或者我应该只使用 GoogleJsonResponseException
但调用它的父 HttpResponseException
方法 getStatusCode()
来查看状态代码,并且只调用 getDetails ()
如果我真的想检查/深入研究任何可能的 Json?
最佳答案
我会将此作为答案发布,以便为处于相同位置的人提供答案,即使它没有解决您提出的具体问题。
一些建议
如果您上传的文件超过 30 个,就会遇到流量控制问题。驱动器的流量控制已损坏,因此您应该自愿节流而不是成为受害者。参见 403 rate limit on insert sometimes succeeds和 403 rate limit after only 1 insert per second
启用 http 日志记录(有关 Java httpcliebnt 的操作方法,请参阅 code.google.com 页面)。这至少可以让您看到响应是什么,并可能提供一些关于如何最好地捕获异常的线索。
您链接到的页面适用于 1.6 版。 afaik 该库目前为 1.19,因此请检查您使用的是最新的库和最新的文档
更令人困惑的是,存在三个独立的库。
- 位于堆栈底部的是 http 库。 https://code.google.com/p/google-http-java-client/
- 上面是通用的 api 库。 https://code.google.com/p/google-api-java-client/和一个 oauth 库 https://code.google.com/p/google-oauth-java-client/
- 顶部是使用新 API 基础架构的各种 Google 服务的库。所以例如。 Drive 库位于 https://developers.google.com/api-client-library/java/apis/drive/v2
关于java - 捕获 GoogleJsonResponseException 但 e.getDetails() 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25587681/