我查看了课程,但看不到在 rails 3 中传递 smtp 电子邮件可能引发的异常列表。
有人知道吗?
我们发现此列表非常适用于您可能想要重试的标准错误:
[ EOFError,
IOError,
TimeoutError,
Errno::ECONNRESET,
Errno::ECONNABORTED,
Errno::EPIPE,
Errno::ETIMEDOUT,
Net::SMTPAuthenticationError,
Net::SMTPServerBusy,
Net::SMTPSyntaxError,
Net::SMTPUnknownError,
OpenSSL::SSL::SSLError
]
请注意,我没有包括在内Net::SMTPFatalError
,因为它通常是永久性故障(例如列入黑名单的电子邮件地址)。
Thoughtbot 上的这篇文章总结了所有可能的 SMTP 异常,并为您提供了一种相当优雅的方式来处理所有这些异常。
http://robots.thoughtbot.com/post/159806037/i-accidentally-the-whole-smtp-exception
以下是可能的例外情况:
SMTP_SERVER_ERRORS = [TimeoutError,
IOError,
Net::SMTPUnknownError,
Net::SMTPServerBusy,
Net::SMTPAuthenticationError]
SMTP_CLIENT_ERRORS = [Net::SMTPFatalError, Net::SMTPSyntaxError]
根据您使用的交付方式,可能会出现更多错误。如果您通过 aws-ses gem 使用 Amazon SES 服务,请将以下错误添加到您的数组
AWS::SES::ResponseError
您可以使用类似这样的代码来捕获错误
# some_utility_class.rb
# Return false if no error, otherwise returns the error
def try_delivering_email(options = {}, &block)
begin
yield
return false
rescue EOFError,
IOError,
TimeoutError,
Errno::ECONNRESET,
Errno::ECONNABORTED,
Errno::EPIPE,
Errno::ETIMEDOUT,
Net::SMTPAuthenticationError,
Net::SMTPServerBusy,
Net::SMTPSyntaxError,
Net::SMTPUnknownError,
AWS::SES::ResponseError,
OpenSSL::SSL::SSLError => e
log_exception(e, options)
return e
end
end
# app/controller/your_controller.rb
if @foo.save
send_email
...
private
def send_email
if error = Utility.try_delivering_email { MyMailer.my_action.deliver_now }
flash('Could not send email : ' + error.message)
end
end