捕获异常时未初始化的常量错误

时间:2011-08-18 06:04:22

标签: ruby exception

我需要通过XMLRPC将文章发布到Wordpress并捕获任何异常:

connection = XMLRPC::Client.new('mysite.com', '/xmlrpc.php', 80)
  connection.call(
  'metaWeblog.newPost',
  1,
  'user',
  'password',
  post,
  true
)

有错误:

C:/Ruby192/lib/ruby/1.9.1/rexml/parsers/baseparser.rb:441:in `rescue in pull': #<NoMethodError: undefined method `[]' for nil:NilClass> (REXML::ParseException)
C:/Ruby192/lib/ruby/1.9.1/rexml/parsers/baseparser.rb:341:in `pull'
C:/Ruby192/lib/ruby/1.9.1/rexml/parsers/streamparser.rb:16:in `parse'
C:/Ruby192/lib/ruby/1.9.1/rexml/document.rb:204:in `parse_stream'
C:/Ruby192/lib/ruby/1.9.1/xmlrpc/parser.rb:717:in `parse'
C:/Ruby192/lib/ruby/1.9.1/xmlrpc/parser.rb:460:in `parseMethodResponse'
C:/Ruby192/lib/ruby/1.9.1/xmlrpc/client.rb:421:in `call2'
C:/Ruby192/lib/ruby/1.9.1/xmlrpc/client.rb:410:in `call'

我成功地抓住了例外:

connection = XMLRPC::Client.new('mysite.com', '/xmlrpc.php', 80)
begin
  connection.call(
    'metaWeblog.newPost',
    1,
    'user',
    'password',
    post,
    true
  )
rescue REXML::ParseException
  puts "Skipping error"
end

帖子还可以,文章在Wordpress中。

接下来我需要捕获有关网站可用性的异常(当网站无法访问时) 我试图通过以下方式捕获异常:

connection = XMLRPC::Client.new('notaccessibleSite.com', '/xmlrpc.php', 80)
begin
  connection.call(
    'metaWeblog.newPost',
    1,
    'user',
    'password',
    post,
    true
  )
rescue REXML::ParseException
  puts "Skipping error"
rescue
  puts "Others errors"
end

但这不起作用:

myscript.rb:47:in `rescue in makeRpc': uninitialized constant Object::REXML (NameError)
from myscript.rb:38:in `makeRpc'
from myscript.rb:62:in `block in postContent'
from myscript.rb:58:in `each'
from myscript.rb:58:in `postContent'
from myscript.rb:71:in `<top (required)>'
from -e:1:in `load'
from -e:1:in `<main>'

有什么建议吗?

3 个答案:

答案 0 :(得分:1)

您是否尝试过require 'rexml/document'。查看rexml/document.rb的文档。它需要'rexml/rexml'以及'rexml/parseexception'

以下内容不会产生任何错误:

require "rexml/document"

begin
    doc = REXML::Document.new File.new('blah.txt')
rescue REXML::ParseException => msg
    puts "Failed: #{msg}"
end

但是,如果您将rexml/document替换为'rexml/rexml',则会获得:

blah.rb:22:in `rescue in <main>': uninitialized constant REXML::ParseException (NameError)
    from abc.rb:20:in `<main>'

更新(根据评论):

如果要检查REXML::ParseException是否已定义,则以下内容将起作用:

if defined?(REXML::ParseException) == 'constant' && REXML::ParseException.class == Class  
  puts "REXML::ParseException is defined"
else
  puts "REXML::ParseException is NOT defined" 
end

答案 1 :(得分:0)

当你测试这个案例时,它似乎无法找到Object :: REXML,也许是rescue NameError拯救了这个。

答案 2 :(得分:0)

您之前必须require 'rexml/rexml'