【发布时间】:2014-01-09 23:11:17
【问题描述】:
鉴于我在 Rails 控制器中有以下人为代码:
class ProfilesController < ApplicationController
def show
@profile = current_user.profile
@content_from_third_party_api = @profile.get_that_third_party_content
end
end
这段代码在views/profiles/show.html.haml:
%h1
Profile Page!
%h2
Data from 3rd party:
= @content_from_third_party_api.first.title
这个人为的代码#get_that_third_party_content:
def get_that_third_party_content
uri = URI.parse("http://api.somesite.com/imfake/")
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.request_uri)
response = http.request(request)
case response.code.to_i
when 200 # the happy path
response
when (400..499)
# What should I do/return here? I have nothing useful to return to the caller.
when (500..599)
# Same goes for here...
end
end
鉴于以下情况,我如何优雅地处理 #get_that_third_party_content 中的超时/错误/等:
- 显示视图期望
@content_from_third_party_api不为零。如果它是 nil,我会在所有地方得到 NilClass 错误 - 显示视图需要渲染一些东西
-
如果出现错误,
#get_that_third_party_content将不返回任何内容 - 感觉我需要做很多 nil 检查......这似乎真的错了
-
rescue_from似乎是一个很好的解决方案,但我不确定这是否很好
【问题讨论】:
-
如果您超时,请
render另一个页面解释出现问题并稍后再试。您还可以存储从这些 API 接收到的任何信息,并在超时、错误等情况下返回存储的信息。 -
这个有规律吗?
标签: ruby-on-rails ruby exception error-handling