我正在使用邮件黑猩猩(通过Gibbon gem)将电子邮件地址添加到我的邮件黑猩猩邮件列表中,我希望处理邮件黑猩猩返回的任何错误,并将它们显示在我的视图中。
这是我的Pages控制器:
class PagesController < ApplicationController
def subscribe
email = subscriber_params[:email]
if email.empty?
flash[:error] = 'Please provide an email.'
redirect_to root_path
else
subscriber = Mailchimp.new.upsert(email)
if subscriber
flash[:success] = 'You\'re in!'
redirect_to root_path(subscribed: :true)
else
# Return error coming from Mailchimp (i.e. Gibbon::MailChimpError)
end
end
end
end下面是我设置的app > services > mailchimp.rb文件,用来分离Mailchimp逻辑:
class Mailchimp
def initialize
@gibbon = Gibbon::Request.new(api_key: Rails.application.credentials.mailchimp[:api_key])
@list_id = Rails.application.credentials.mailchimp[:list_id]
end
def upsert(email)
begin
@gibbon.lists(@list_id).members.create(
body: {
email_address: email,
status: "subscribed"
}
)
rescue Gibbon::MailChimpError => e #This is at the bottom of the Gibbon README
raise e.detail
end
end
end我想弄清楚的是如何在我的Pages#subscribe操作中返回/发送Gibbon::MailChimpError。我看到它在控制台中作为RuntimeError输出,但我不确定访问/传递它的正确方式。
如果有更好的实现方法,请告诉我。
发布于 2019-12-30 13:51:05
您可以将begin/rescue块移动到控制器中的subscribe操作,以便从那里处理错误,或者更好的做法是,您可以在控制器中使用rescue_from,如下所示:
class PagesController < ApplicationController
rescue_from Gibbon::MailChimpError do |e|
# Handle the exception however you want
end
def subscribe
# ....
end
endhttps://stackoverflow.com/questions/59507460
复制相似问题