'Comparison of exception message always fails in if my statement

I have this variable in my Constants class:

public static final String EXCEPTION_STRING= "My Exceptions message";

I want to check for it in my catch and throw a particular message if it's found. This is what I came up with:

} catch (Exception e) {
    if (e.getMessage().equals(Constants.EXCEPTION_STRING)) {
        throw new ServiceException(MyClassName.class.toString(),
            Constants.EXCEPTION_STRING);
    } else {
        LOGGER.info("Save failed: " + e);
    }
}

The if never seems to get entered even though I can see the correct exception message. What am I doing wrong?



Solution 1:[1]

Does your own custom exception get wrapped in another exception? In that case you need to do something like:

e.getCause().getMessage()

Solution 2:[2]

This is what I did:

} catch (Exception e) {
    if (e instanceof AxisFault) {
        if (e.getMessage().equals(Constants.EXCEPTION_STRING)) {
            throw new ServiceException(MyClassName.class.toString(),
                Constants.EXCEPTION_STRING);
        }
    } else {
        LOGGER.info("Save failed: " + e);
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Johan Nordlinder
Solution 2 runnerpaul