Uninitialized Constant Error when catching Exception
I need to post articles to Wordpress via XMLRPC and catch any exceptions:
connection = XMLRPC::Client.new('mysite.com', '/xmlrpc.php', 80)
connection.call(
'metaWeblog.newPost',
1,
'user',
'password',
post,
true
)
There is en error:
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'
I successfully caught the exception with:
connection = XMLRPC::Client.new('mysite.com', '/xmlrpc.php', 80)
beg开发者_C百科in
connection.call(
'metaWeblog.newPost',
1,
'user',
'password',
post,
true
)
rescue REXML::ParseException
puts "Skipping error"
end
Post is OK, article is in Wordpress.
Next I needed to catch an exception about site availability (when site is not accessible) I tried to catch the exception with:
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
But this does not work:
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>'
Any suggestions?
Have you tried require 'rexml/document'
. Have a look at the documentation for rexml/document.rb. It requires 'rexml/rexml'
for you as well as 'rexml/parseexception'
.
The following doesn't produce any errors:
require "rexml/document"
begin
doc = REXML::Document.new File.new('blah.txt')
rescue REXML::ParseException => msg
puts "Failed: #{msg}"
end
However if you replace the rexml/document
with 'rexml/rexml'
, you get:
blah.rb:22:in `rescue in <main>': uninitialized constant REXML::ParseException (NameError)
from abc.rb:20:in `<main>'
Update (based on comments):
If you want to check that REXML::ParseException
is defined, something like the following will work:
if defined?(REXML::ParseException) == 'constant' && REXML::ParseException.class == Class
puts "REXML::ParseException is defined"
else
puts "REXML::ParseException is NOT defined"
end
Seems that it can't find Object::REXML when you are testing this case, maybe a rescue NameError
rescues this.
You must require 'rexml/rexml'
before.
精彩评论