Timeouts and Errors
Stay organized with collections
Save and categorize content based on your preferences.
AI-generated Key Takeaways
-
You can set connect and read timeouts for Google API requests using the
setConnectTimeoutandsetReadTimeoutmethods with the Google API Client Library for Java. -
When an HTTP error status code is returned from a Google API using the JSON format, a
GoogleJsonResponseExceptionis thrown. -
You can handle HTTP errors from Google APIs by catching the
GoogleJsonResponseExceptionand accessing its details.
This document describes how to set timeouts and handle HTTP errors that your code might receive when you use the Google API Client Library for Java.
Contents
Setting timeouts
In the following example, which uses the Google Analytics API, the
setConnectTimeout and setReadTimeout methods are used to set the connect and
read timeouts to three minutes (in milliseconds) for all requests:
privateHttpRequestInitializersetHttpTimeout(finalHttpRequestInitializerrequestInitializer){
returnnewHttpRequestInitializer(){
@Override
publicvoidinitialize(HttpRequesthttpRequest)throwsIOException{
requestInitializer.initialize(httpRequest);
httpRequest.setConnectTimeout(3*60000);// 3 minutes connect timeout
httpRequest.setReadTimeout(3*60000);// 3 minutes read timeout
}
};
GoogleCredentialcredential=....
finalAnalyticsanalytics=Analytics.builder(newNetHttpTransport(),jsonFactory,setHttpTimeout(credential)).build();
Handling HTTP error responses from Google APIs
When an error status code is detected in an HTTP response to a Google API that uses the JSON format, the generated libraries throw a GoogleJsonResponseException.
The errors use the format specified in Error responses.
The following example shows one way that you can handle these exceptions:
Drive.Files.ListlistFiles=drive.files.list();
try{
FileListresponse=listFiles.execute();
...
}catch(GoogleJsonResponseExceptione){
System.err.println(e.getDetails());
}