【问题标题】:Ruby NameError undefined local variable or method `eRuby NameError 未定义的局部变量或方法`e
【发布时间】:2011-08-28 18:34:33
【问题描述】:
class TwitterProfile < ActiveRecord::Base

  def send_status_update(status_update)
    if publish?
      client = Twitter::Client.new( :oauth_token => authentication.token,
                           :oauth_token_secret => authentication.secret)
      client.update(status_update.to_twitter_string)
    end
  rescue Exception => e
    logger.info "Error publishing to twitter: #{e.to_s}"
  end
end

有一个 StatusUpdate 模型和一个观察者将它们转发到 Twitter after_create。我有时会遇到以下异常:

NameError (undefined local variable or method `e' for #<TwitterProfile:0x00000004e44ab8>):
app/models/twitter_profile.rb:23:in `rescue in send_status_update'
app/models/twitter_profile.rb:18:in `send_status_update'
app/models/status_update_observer.rb:6:in `block in after_create'
app/models/status_update_observer.rb:4:in `after_create'
app/models/workout_observer.rb:5:in `after_update'
app/controllers/frames_controller.rb:76:in `update'
app/controllers/application_controller.rb:24:in `call'
app/controllers/application_controller.rb:24:in `block (2 levels) in <class:ApplicationController>'
app/controllers/application_controller.rb:10:in `block in <class:ApplicationController>'

我在这里错过了什么?

【问题讨论】:

  • 这很奇怪,但很有趣,看起来它的行为就像 =&gt; e 不存在一样。
  • 注意:不要救援Exception——而是救援StandardError。见thattommyhall.com/2011/02/24/…

标签: ruby exception


【解决方案1】:

我有一件事我知道,另一件事只是猜测。

我知道的是,您不需要在整个 #{} 表达式上调用 to_s;这将自动发生。但这并没有什么坏处。

我的猜测是您的测试用例并没有真正运行您发布的代码。如果将e 更改为f 会发生什么?

我应该注意,拯救 Exception 本身通常是一个坏主意。您应该在最高级别挽救 RuntimeError 或 StandardError,最好是更具体的。抢救 Exception 时可能会出现相当奇怪的错误,因为您会干扰线程和解释器级别的事件。

【讨论】:

  • 将方法更改为仅救援 Twitter::Error。对其进行测试,看看是否能解决问题。
【解决方案2】:

您缺少开始/救援子句的“开始”块。

【讨论】:

  • 不,你可以用这种语法在函数中救援,这是有效的 ruby​​。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-19
  • 1970-01-01
  • 2016-02-14
  • 2016-04-08
相关资源
最近更新 更多