Rails错误检查电子邮件传递 - deliver_now

时间:2015-10-07 18:16:23

标签: ruby-on-rails-4 error-handling try-catch email-delivery

我应该如何包装deliver_now方法调用,以便在发送时发现错误?

@user = User.new(user_params)
if @user.valid?
  MyMailer.user_email(@user).deliver
  # hmmm....  how do we catch if the email is not sent?  
else
  ...
end

1 个答案:

答案 0 :(得分:2)

确保在应用程序配置中设置了config.action_mailer.raise_delivery_errors = true。然后你可以用救援块捕获异常。像这样:

@user = User.new(user_params)
if @user.valid?
  begin
    MyMailer.user_email(@user).deliver
  rescue StandardError => e
    # do something with the messages in exception object e
    flash[:error] = 'Problems sending email'
  end
else
  ...
end