如何捕获Storage.Objects.Insert请求failure/errors?
How to capture Storage.Objects.Insert request failure/errors?
这是我将文件上传到 Google 云存储的代码,
public static void uploadFile(String name, String contentType, File file, String bucketName)
throws IOException, GeneralSecurityException {
InputStreamContent contentStream = new InputStreamContent(contentType, new FileInputStream(file));
// Setting the length improves upload performance
contentStream.setLength(file.length());
StorageObject objectMetadata = new StorageObject()
// Set the destination object name
.setName(name)
// Set the access control list to publicly read-only
.setAcl(Arrays.asList(new ObjectAccessControl().setEntity("allUsers").setRole("READER")));
// Do the insert
Storage client = StorageFactory.getService();
Storage.Objects.Insert insertRequest = client.objects().insert(bucketName, objectMetadata, contentStream);
StorageObject response =insertRequest.execute();
System.out.println("Storage insert response: "+response.toPrettyString());
}
如何从响应对象中捕获错误?
响应对象中不会存在错误。相反,您会看到生成了一个异常。您可以 catch (GoogleJsonResponseException e)
并检查 e.getDetails()
中的 GoogleJsonError
。参见 an example。其他例外情况也适用,包括一些从未产生 JSON 输出的情况。
这是我将文件上传到 Google 云存储的代码,
public static void uploadFile(String name, String contentType, File file, String bucketName)
throws IOException, GeneralSecurityException {
InputStreamContent contentStream = new InputStreamContent(contentType, new FileInputStream(file));
// Setting the length improves upload performance
contentStream.setLength(file.length());
StorageObject objectMetadata = new StorageObject()
// Set the destination object name
.setName(name)
// Set the access control list to publicly read-only
.setAcl(Arrays.asList(new ObjectAccessControl().setEntity("allUsers").setRole("READER")));
// Do the insert
Storage client = StorageFactory.getService();
Storage.Objects.Insert insertRequest = client.objects().insert(bucketName, objectMetadata, contentStream);
StorageObject response =insertRequest.execute();
System.out.println("Storage insert response: "+response.toPrettyString());
}
如何从响应对象中捕获错误?
响应对象中不会存在错误。相反,您会看到生成了一个异常。您可以 catch (GoogleJsonResponseException e)
并检查 e.getDetails()
中的 GoogleJsonError
。参见 an example。其他例外情况也适用,包括一些从未产生 JSON 输出的情况。