如何捕获Storage.Objects.Insert请求失败/错误?

时间:2016-09-11 11:35:09

标签: google-cloud-storage

以下是将文件上传到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());

}

如何从响应对象中捕获错误?

1 个答案:

答案 0 :(得分:0)

错误在响应对象中不存在。相反,您将看到生成异常。您可以catch (GoogleJsonResponseException e)并检查GoogleJsonError中的e.getDetails()。见an example。可以应用其他异常,包括一些从不产生JSON输出的异常。

相关问题