I have this snippet of code to deal with catching particular exceptions
private static final String CONNECTION_REFUSED_EXCEPTION = "java.net.ConnectException: Connection refused: connect";
...
} catch (org.apache.axis.AxisFault af) {
if (af.getFaultString().equals(CONNECTION_REFUSED_EXCEPTION))
{
// Do something
}
}
This works fine locally on my windows development environment
However, when I deploy to a unix machine for testing, the fault string differs, as show below (note the : connect missing from the end)
- Windows fault string :
java.net.ConnectException: Connection
refused: connect - Unix fault string :
java.net.ConnectException: Connection
refused
Why is this so?
For the record, I believe the following would be better suited for matching the fault string :
...
if(af.getCause() instanceof java.net.ConnectException)
...
The ‘fault string’ messages are meant to provide additional information for debugging purposes. They can vary in different implementations, versions, or environments. The same applies in general to all Exception message strings (
Throwable.getMessage()).Application code should not rely on the exact text of Exception messages in order to identify the cause of the exception. Your suggestion of using
instanceofinstead to check the cause of the exception is a much better solution.Edit:
If you absolutely need to check the detail message, as it seems to happen in your case (because
getCause()is returningnull), then I would recommend to check whether the detail message contains the name of the specific wrapped exception you are checking for (e.g.java.net.ConnectException). This is after all the same information you would be getting ifgetCause()wasn’t returningnullin the first place, and should minimize dependencies with the exact text of the detail message.