java - 如何检查 Throwable 是否是由无效电子邮件地址导致的

标签 java exception jakarta-mail

注意:我当前的解决方案正在运行(我认为)。我只是想确保我没有遗漏任何东西。

我的问题:我想知道如何检查是否因电子邮件地址无效而导致异常。使用 Java 邮件。

目前我正在检查SMTPAddressFailedExceptiongetAddress()AddressExceptiongetRef() .

这是我当前进行检查的方法。 我错过了什么吗?

/**
* 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 ),这就是最初引发错误的地方。

最佳答案

您通常不需要强制转换异常;这就是为什么你可以有多个 catch block :

try {
    // code that might throw AddressException
} catch (SMTPAddressFailedException ex) {
    // Catch subclass of AddressException  first
    //  ...
} catch (AddressException ex) {
    // ...
}

如果担心嵌套异常,可以使用Guava的Throwables.getRootCause

关于java - 如何检查 Throwable 是否是由无效电子邮件地址导致的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11866717/

相关文章:

c++ - 捕获 boost::interrupted_exception 是否正确?

exception - 使用 Clojure 处理异常

c++ - MFC CDatabase::OpenEx 函数如何知道它在 try/catch block 中?

java - 如何通过 Java 从 Outlook 发送电子邮件?

java - 是否有带有 SQL 后端的 Javamail 商店?

JavaMail 在同一线程/对话中发送电子邮件

java - 我做了什么使 "weak refs processing"需要 30 秒而不是 1.5 秒?

java - 无法呈现推文

java - 框架 setVisible(false) 和 dispose() 无法杀死进程

java - 是否可以在 android listview 分隔符中添加 xml 布局?