注意:我当前的解决方案正在运行(我认为)。我只是想确保我没有遗漏任何东西。
我的问题:我想知道如何检查是否因为无效的电子邮件地址而导致异常。使用Java Mail。
目前,我正在使用SMTPAddressFailedException和getAddress() AddressException检查getRef()。
这是我目前进行检查的方法。 我错过了什么吗?
/**
* 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;
}
注意:如果您感到好奇(或者它很有用),我会使用Java Helper Library发送电子邮件(请参阅此line),以便最初抛出错误。< / p>
答案 0 :(得分:2)
通常不需要施放异常;这就是为什么你可以有多个catch块:
try {
// code that might throw AddressException
} catch (SMTPAddressFailedException ex) {
// Catch subclass of AddressException first
// ...
} catch (AddressException ex) {
// ...
}
如果您担心嵌套异常,可以使用Guava的Throwables.getRootCause
。