如何用法拉​​第捕获Faraday :: Error :: ConnectionFailed异常?

时间:2013-02-18 17:39:47

标签: faraday

如果我从法拉第运行HTTP请求,而网络不可用(即在wifi环境或离线工作),默认情况下有一些东西可以捕获此异常:

/Users/pmu/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/net/http.rb:762:in `initialize': getaddrinfo: nodename nor servname provided, or not known (Faraday::Error::ConnectionFailed)
    from /Users/pmu/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/net/http.rb:762:in `open'
    from /Users/pmu/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/net/http.rb:762:in `block in connect'
    from /Users/pmu/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/timeout.rb:54:in `timeout'
    from /Users/pmu/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/timeout.rb:99:in `timeout'
    from /Users/pmu/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/net/http.rb:762:in `connect'
    from /Users/pmu/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/net/http.rb:755:in `do_start'
    from /Users/pmu/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/net/http.rb:744:in `start'
    from /Users/pmu/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/net/http.rb:1284:in `request'
    from /Users/pmu/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/net/http.rb:1026:in `get'
    from /Users/pmu/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/faraday-0.8.5/lib/faraday/adapter/net_http.rb:73:in `perform_request'
    from /Users/pmu/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/faraday-0.8.5/lib/faraday/adapter/net_http.rb:38:in `call'
    from /Users/pmu/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/faraday-0.8.5/lib/faraday/response.rb:8:in `call'
    from /Users/pmu/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/faraday-0.8.5/lib/faraday/response/logger.rb:20:in `call'
    from /Users/pmu/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/faraday-0.8.5/lib/faraday/request/authorization.rb:36:in `call'
    from /Users/pmu/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/faraday-0.8.5/lib/faraday/request/url_encoded.rb:14:in `call'
    from /Users/pmu/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/faraday-0.8.5/lib/faraday/request/multipart.rb:13:in `call'
    from /Users/pmu/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/faraday-0.8.5/lib/faraday/connection.rb:245:in `run_request'
    from /Users/pmu/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/faraday-0.8.5/lib/faraday/connection.rb:98:in `get'
    from /Users/pmu/projects/bar/cli/lib/foo/rest_client.rb:32:in `list'

默认情况下如何才能让法拉第抓住这个问题?

1 个答案:

答案 0 :(得分:4)

如果你想要它做一些比完整的堆栈跟踪更好的事情,你可以在你的法拉第设置的基础上做这样的事情:

begin
 @app.call(env)
rescue Faraday::Error::ConnectionFailed => e
  puts "Connection failed: #{e}"
  # Choose what you want to happen, for example in my gem I do
  exit 1
end