views:

86

answers:

3

When using java.net.Socket.connect(), both a refused connection and a timeout result in a ConnectException.

java.net.ConnectException: Connection timed out: connect

java.net.ConnectException: Connection refused: connect

How can I safely distinguish between the two? Sure parsing the error message does the job. But when the message changes in a future Java release, I'm out of luck.

The bigger picture: I'm writing a web service client using JAX-WS with a Metro implementation. When a web service call fails, I want to report the reason for the failure clearly so the issue can be resolved quickly.

A: 

Check the error message (like you mentioned), but abstract it away.

If it changes in a future Java release, you change it in the abstraction and leave the core of your code alone.

Stargazer712
This will break immediately if the JVM has localized messages.
Thorbjørn Ravn Andersen
+2  A: 

Measure the time passed between invoking connect() and the exception was thrown, and pass that information on.

Thorbjørn Ravn Andersen
+1  A: 

Unfortunately, in the Sun JDK, this information isn't made available anywhere but the string. See line 473 of PlainSocketImpl.c (for *ix), and net_util_md.c (for Windows). The *ix implementation does sometimes call NET_ThrowByNameWithLastError (from *ix net_util_md.c), which will include errno in the string; this function exists on Windows, but it's not used here..

Thus, you have to rely on the strings and hope they don't change. Sun does not seem to localize them, which makes sense because they're not supposed to be user-facing. You can try to parse the errno out for a more stable error code.

You should also be sure to have a fall-back in case no string or errno matches.

Matthew Flaschen
Having a fallback is an acceptable solution.
Stijn Van Bael
I like this answer, but maintain my former suggestion: abstract it away! The last thing you want is a bunch of inconsistent and repetitious checks on an interface that you cannot rely on. Create an interface that makes sense to you, and abstract away the details. You do not want to be editing a dozen files if anything changes.
Stargazer712