Note: My current solution is working (I think). I just want to make sure I’m not missing anything.
My question: I’m wondering how to check whether an exception was caused because an invalid e-mail address. Using Java Mail.
Currently I’m checking SMTPAddressFailedExceptions with getAddress() and AddressExceptions with getRef().
Here’s my current method for conducting the check. Am I missing anything?
/**
* Checks to find an invalid address error in the given exception. Any found will be added to the ErrorController's
* list of invalid addresses. If an exception is found which does not contain an invalid address, returns false.
*
* @param exception the MessagingException which could possibly hold the invalid address
* @return if the exception is not an invalid address exception.
*/
public boolean handleEmailException(Throwable exception) {
String invalidAddress;
do {
if (exception instanceof SMTPAddressFailedException) {
SMTPAddressFailedException smtpAddressFailedException = (SMTPAddressFailedException) exception;
InternetAddress internetAddress = smtpAddressFailedException.getAddress();
invalidAddress = internetAddress.getAddress();
} else if (exception instanceof AddressException) {
AddressException addressException = (AddressException) exception;
invalidAddress = addressException.getRef();
}
//Here is where I might do a few more else ifs if there are any other applicable exceptions.
else {
return false;
}
if (invalidAddress != null) {
//Here's where I do something with the invalid address.
}
exception = exception.getCause();
} while (exception != null);
return true;
}
Note: In case you’re curious (or it’s helpful), I use the Java Helper Library to send the e-mail (see this line) so that’s where the error is thrown initially.
You shouldn’t usually need to cast exceptions; that’s why you can have multiple catch blocks:
If you are worried about nested exceptions, you can use Guava’s
Throwables.getRootCause.