问题
While trying to develop an application that interacts with some cloud services I found the Dropbox API for Java to be especially confusing.
Specifically how to find the HTTP errors. For instance, with the Google Drive API if a request fails an IOException will be thrown however you can parse that IOException into a GoogleJsonResponseException which you can then extract the status code.
try {
File f =drive.files().create(fileMetadata).setFields("id").execute();
return f.getId();
} catch (IOException e) {
if (e instanceof GoogleJsonResponseException){
int statusCode = ((GoogleJsonResponseException) e).getStatusCode();
errorHandler(statusCode);
} else {
e.printStackTrace();
}
}
So is there something like this in the java dropbox API (Specifically 3.0.5). I have been looking around and it seems like no but I wanted to make sure before I go down the rabbit hole of extremely specialized and complex coding like mentioned here. If it is could someone please give me an example of how I could properly handle these exceptions.
回答1:
[Cross-linking for reference: https://www.dropboxforum.com/t5/API-support/How-to-get-error-responses-java-api/m-p/258338#M14989 ]
The Dropbox Java SDK automatically parses out the structured error data from the HTTPS response into native classes, and you can use as much or little of that specificity as you want. The structured error responses (generally JSON in the response body) offer much more granularity than just status codes.
For example, here's the code sample that is now missing from StackOverflow documentation from my post that you linked to:
try {
SharedLinkMetadata sharedLinkMetadata = client.sharing().createSharedLinkWithSettings("/test.txt");
System.out.println(sharedLinkMetadata.getUrl());
} catch (CreateSharedLinkWithSettingsErrorException ex) {
System.out.println(ex);
} catch (DbxException ex) {
System.out.println(ex);
}
And here's an example that shows how to check for a particular error case (i.e., a "path" error in that example).
That's the recommended way of handling these exceptions. I don't believe the SDK offers a way to retrieve the original unparsed error response. (If you don't want to use the SDK though, you can call the HTTPS endpoints yourself directly.)
来源:https://stackoverflow.com/questions/48036981/how-to-deal-with-errors-in-the-dropbox-java-api