Reputation: 2043
I am trying to extend some legacy code to make it more tolerant of network outages. I have some (legacy) groovy code which wraps up a call to a webservice (CallWebService) via wslite. Sometimes, this call throws either a wslite.http.HTTPClientException or a java.net.ConnectException exception (this has been determined by adding
log.info("Exception " + ex.getClass().getName() + " throw");
to my log4j logging)
The code which calls this groovy code is in java and looks like the following:
public static String getDataFromWebService(String webServiceUrl, String referenceNumber) {
try {
ReturnedData returnedData = new CallWebService(webServiceUrl, referenceNumber);
return (String)returnedData.toXml();
}
catch (Exception ex) {
log.info("Exception caught: class of exception is " + ex.getClass().getName());
throw ex;
}
What I want to do, is catch the thrown exception (wslite.http.HTTPClientException or java.net.ConnectException) and retry the call (as it's probably a glitch) once or twice.
When I try and add
catch (java.net.ConnectException ex)
and build, the build fails with
exception ConnectException is never thrown in body of corresponding try statement
What should I do to be able to catch and react to the appropriate exceptions?
Upvotes: 2
Views: 5640
Reputation: 28757
In your Java code, I would do something like this:
try {
callGroovy();
} catch (RuntimeException e) { // EDIT --- Should be Exception, RuntimeException
if (e instanceof HTTPClientException || e.getCause() instanceof ConnectException) {
throw e;
}
// log other exception...
}
This would be a bit safer than catching single exception types. In my experience, dynamic languages like groovy are more likely to throw unanticipated runtime exceptions. And catching all runtime exceptions would ensure that groovy exceptions do not infect the rest of your program.
Upvotes: 2