Title: meaningful errors from HttpURLConnection
Tags: java;android;http
Question: I use the following code to post a HTTP GET and retrieve a response:
boolean download(String url)
java.net.URL connectURL = new URL(url);
HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("GET");
conn.connect();
conn.getOutputStream().flush();
try( InputStream is = conn.getInputStream() )
{
int ch;
StringBuilder sb = new StringBuilder();
while( ( ch = is.read() ) != -1 )
{
sb.append( (char)ch );
}
mScores = sb.toString();
}
catch( final Exception e)
{
mReceiver.exception("biffed it getting HTTPResponse");
return false;
}
catch( final Exception e )
mReceiver.exception(e.getMessage());
return false;
return true;
It's all working nicely, except the error cases. If, for example, I switch off access to Internet on the device this code runs on and try
download("http://example.com/download.cgi");
then the exception ( mReceiver.exception(e.getMessage()) above ) that my user sees is
Unable to resolve host 'example.com': No address associated with hostname
which might be understandable to developers, but IMHO is not user-friendly enough. I'd like something like "No access to Internet, failed to reach server 'example.com'" or maybe even simpler 'No access to Internet'.
Thus my question is: is there a way to return meaningful, user-friendly error strings from above code?

Here is the accepted answer: Well, you can catch specific types of exceptions (this needs to go before catch(final Exception e)):
catch( final java.net.UnknownHostException e )
mReceiver.exception("No access to Internet, failed to reach server '" + url + "'");
return false;
Comment for this answer: @Leszek FWIW, exceptions/errors aren't really meant to be useful to users, so you reap very little benefit from doing this. As long as you can reason about the exceptions Java produces, it shouldn't really matter. What's usually the bigger concern is divulging too much info to the user (stack trace, other debugging info)
Comment for this answer: Well, yeah, obviously. I guess I just need to read up on all exceptions those calls might generate and decide on appropriate error strings... Thanks.


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2020:00:02/11/20', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<java><android><http>', 'Title': 'meaningful errors from HttpURLConnection', 'ViewCount': 22, 'id': 60173577, 'user_AboutMe': '', 'user_AccountId': 284765.0, 'user_DisplayName': 'Leszek', 'user_Reputation': 1151.0, 'user_Views': 137.0, 'user_id': 583075.0}}