我正在学习如何在我的rails应用程序中实现第三方app,但很难处理错误响应。
更具体地说,我正在尝试用gem 全接触API实现富尔接触-api-红宝石。我已经使用API密钥对身份验证进行了排序,并通过控制台使用gem方法进行了一些请求,没有出现问题。
我现在尝试在Profiles Controller中使用API包装方法。其想法是:
我开始写这样的代码:
# controllers/profiles_controller.rb
def create
@intel = FullContact.person(email: params[:email])
if @intel[:status].to_s[0] != "2"
flash[:error] = @intel[:status]
redirect_to profiles_path
else
# Code to create and populate a Profile instance
end由于成功响应在200 s中有状态代码,我假设我将从Json对象中提取代码,并检查它是否以2开头,在这种情况下,我将继续创建实例。如果响应正常,这类方法可以工作,因为我可以使用存储在@intel中的Json对象。但是,当响应位于400 s时,500 s Rails触发一个异常,Rails崩溃,Rails不允许我处理任何JSON对象:
FullContact::NotFound in ProfilesController#create
GET https://api.fullcontact.com/v2/person.json?apiKey=MY_API_KEY&email=THE_EMAIL_IM_USING_AS_PARAMETER: 404很明显我做错了什么。我尝试过避免rescue StandardError => e引发的异常,但我想知道在我的控制器中处理这个错误的正确方法是什么。有什么帮助吗?
--更新1尝试史蒂夫解决方案--
如果我只是在请求之后拯救了这个例外,像这样:
def create
@intel = FullContact.person(email: params[:email])
rescue FullContact::NotFound
if @intel.nil?
flash[:error] = "Can't process request try again later"
redirect_to profiles_path
else
# Code to create and populate a Profile instance
end@intel设置为nil (即未设置为响应JSON对象)。我想我只是更改了条件,以检查@intel是否为空,但是由于一些奇怪的原因,当响应成功并且@intel被设置为JSON对象时,第一个条件并不会导致创建对象的方法。即使响应失败,也不确定如何将@intel设置为JSON响应。
发布于 2017-07-30 10:44:00
rescue块的思想是定义在避免错误时发生的操作。
构造你的方法的正确方法是..。
def create
@intel = FullContact.person(email: params[:email])
# Code to create and populate a Profile instance
rescue FullContact::NotFound
flash[:error] = "Can't process request try again later"
redirect_to profiles_path
end 被救出时执行rescue后出现的代码,否则将被忽略。
格式是
begin
# normal code which may or may not encounter a raised error, if no
# raised error, it continues to normal completion
rescue
# code that is only executed if there was a rescued error
ensure
# code that always happens, regardless of rescue or not, could be
# used to ensure necessary cleanup happens even if an exception raised
end方法本身就是一个完整的begin块,因此不需要上述格式大纲中的begin和end。
您不需要使用ensure块,只需添加它来证明该功能的存在。还有可能将else与rescue一起使用,但这还需要一天的时间:)
发布于 2017-07-29 12:31:35
你能做到的
rescue FullContact::NotFound来弥补这个错误。
看起来,错误不会让您的比较发生。即使如此,你的比较还是有缺陷的。由于要将其转换为字符串,所以需要将其与字符串进行比较
变化
if @intel[:status].to_s[0] != 2转到
if @intel[:status].to_s[0] != '2'https://stackoverflow.com/questions/45388863
复制相似问题