0

我正在使用 Rails 框架。我正在使用“media_wiki”宝石。我希望捕捉到“缺少标题”错误。见下文

mw = MediaWiki::Gateway.new('http://en.wikipedia.org/w/api.php/')
wiki_content = mw.render('msadb')

它导致了一个错误

MediaWiki::APIError: MediaWiki::APIError: API error: code 'missingtitle', info 'The page you specified doesn't exist'
from /home/papri/.rvm/gems/ruby-1.9.3-p194/gems/mediawiki-gateway-0.5.0/lib/media_wiki/gateway.rb:711:in `get_response'
from /home/papri/.rvm/gems/ruby-1.9.3-p194/gems/mediawiki-gateway-0.5.0/lib/media_wiki/gateway.rb:669:in `block in make_api_request'
from /home/papri/.rvm/gems/ruby-1.9.3-p194/gems/rest-client-1.6.7/lib/restclient/request.rb:228:in `call'
from /home/papri/.rvm/gems/ruby-1.9.3-p194/gems/rest-client-1.6.7/lib/restclient/request.rb:228:in `process_result'
from /home/papri/.rvm/gems/ruby-1.9.3-p194/gems/rest-client-1.6.7/lib/restclient/request.rb:178:in `block in transmit'
from /home/papri/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/net/http.rb:745:in `start'
from /home/papri/.rvm/gems/ruby-1.9.3-p194/gems/rest-client-1.6.7/lib/restclient/request.rb:172:in `transmit'
from /home/papri/.rvm/gems/ruby-1.9.3-p194/gems/rest-client-1.6.7/lib/restclient/request.rb:64:in `execute'
from /home/papri/.rvm/gems/ruby-1.9.3-p194/gems/rest-client-1.6.7/lib/restclient/request.rb:33:in `execute'
from /home/papri/.rvm/gems/ruby-1.9.3-p194/gems/rest-client-1.6.7/lib/restclient.rb:72:in `post'
from /home/papri/.rvm/gems/ruby-1.9.3-p194/gems/mediawiki-gateway-0.5.0/lib/media_wiki/gateway.rb:692:in `http_send'
from /home/papri/.rvm/gems/ruby-1.9.3-p194/gems/mediawiki-gateway-0.5.0/lib/media_wiki/gateway.rb:661:in `make_api_request'
from /home/papri/.rvm/gems/ruby-1.9.3-p194/gems/mediawiki-gateway-0.5.0/lib/media_wiki/gateway.rb:106:in `render'
from (irb):18
from /home/papri/.rvm/gems/ruby-1.9.3-p194/gems/railties-3.2.6/lib/rails/commands/console.rb:47:in `start'
from /home/papri/.rvm/gems/ruby-1.9.3-p194/gems/railties-3.2.6/lib/rails/commands/console.rb:8:in `start'
from /home/papri/.rvm/gems/ruby-1.9.3-p194/gems/railties-3.2.6/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'

当我尝试使用救援开始循环来捕捉这个错误时,它没有用。

mw = MediaWiki::Gateway.new('http://en.wikipedia.org/w/api.php/')
begin
wiki_content = mw.render('msadb')
rescue
print "This is a missing title error"
end

输出与之前的错误相同。Rescue begin 无法捕获此错误。我应该如何捕捉这个错误。

4

1 回答 1

0

MediaWiki::APIError不是StandardError后代,这就是默认rescue语句不捕获它的原因(请参阅:“如果您编写没有参数列表的救援子句,则参数默认为 StandardError。”)

因此,您需要MediaWiki::APIError在救援子句中明确指定:

mw = MediaWiki::Gateway.new('http://en.wikipedia.org/w/api.php/')
begin
  wiki_content = mw.render('msadb')
rescue MediaWiki::APIError => e
  print "This is a missing title error"
end

# ⇒ This is a missing title error => nil 
于 2013-02-16T06:22:03.140 回答