I am implementing an API call to the MailChimp API in my web application. But this question is valid for any call to an API which accepts a simple HTTP GET.
I would like to catch any errors and allow my application to continue without issues even if the API call failed, The mailchimp servers and down, slow or unavailable.
MailChimp API Returns a serialized JSON Object. This is my code.
def listSubscribe = { apiurl, apikey, listid, email ->
def url = "${apiurl}?method=listSubscribe&apikey=${apikey}&id=${listid}&email_address=${email}"
}
try {
def url = new URL(listSubscribe(apiUrl,apiKey,listId,email))
return (url.text == 'true') ? true : false
} catch (MalformedURLException e) {
return false
} catch (java.net.UnknownHostException e) {
return false
}
Should I perform any other try/catch? How can I improve my code to make it safer for inaccesible API calls?
Solution
In order to make the call asynchronous and since I am using this code inside a Grails application I created a Quartz Job to execute the service containing the API Call.
class MailChimpListSubscribeJob {
def mailChimpService
def execute(context) {
mailChimpService.listSubscribe(context.mergedJobDataMap.get('email'))
}
}
The Service now uses a timeout and catches the generic Exception:
class MailChimpService {
def grailsApplication
def listSubscribe(email_address) {
def apiurl = grailsApplication.config.mailchimp.apiUrl
def apikey = grailsApplication.config.mailchimp.apiKey
def listid = grailsApplication.config.mailchimp.listId
listSubscribe(apiurl, apikey, listid, email_address)
}
def listSubscribe(apiurl, apikey, listid, email) {
try {
def cmdurl = "${apiurl}?method=listSubscribe&apikey=${apikey}&id=${listid}&email_address=${email}"
def url = new URL(cmdurl)
def response = url.getText(connectTimeout: 4 * 1000, readTimeout: 4 * 1000)
return (response == 'true') ? true : false
} catch (MalformedURLException e) {
return false
} catch (java.net.UnknownHostException e) {
return false
} catch (Exception e) {
return false
}
}
}
And inside my controllers:
MailChimpListSubscribeJob.triggerNow([email: 'myemail@example.com'])
Sergio – You may also want to do the following: