Ruby-从解析的XML中解救多个赋值
我使用Nokogiri解析了一些XML,如下所示:Ruby-从解析的XML中解救多个赋值,ruby,Ruby,我使用Nokogiri解析了一些XML,如下所示: doc=Nokogiri::XML(有效负载) 现在我已经创建了一个对象,我正在使用解析后的XML为其分配一些属性 如果由于任何原因数据丢失或XML解析不正确,我希望向我提供适当的消息。我已经做到了: fm = BigMessage.new begin fm.title = doc.children.at('title').child.content fm.languagecode = doc.children.at('languag
doc=Nokogiri::XML(有效负载)
现在我已经创建了一个对象,我正在使用解析后的XML为其分配一些属性
如果由于任何原因数据丢失或XML解析不正确,我希望向我提供适当的消息。我已经做到了:
fm = BigMessage.new
begin
fm.title = doc.children.at('title').child.content
fm.languagecode = doc.children.at('language').child.content
fm.description = doc.children.at('description').child.content
rescue => e
log_err("Could not update - reason #{e}")
end
但是-错误只是显示未捕获异常
。是否可以说是由于将fm.title赋值为null而导致的错误
这真的是最好的处理方法吗
谢谢。记录您可以通过e.message
获得的实际错误消息,这样您的日志行将如下所示:
log_err(“无法更新-原因{e.message}”)
话虽如此,消息仍然不会像您所要求的那样包含上下文数据
为了获得更多的上下文数据,您必须尝试单独读取/设置每个属性,如果失败,您将知道失败的属性是什么
要做到这一点,它可能类似于以下伪代码:
fm = BigMessage.new
properties = [:title, :language, :description]
properties.each do |property|
begin
value = doc.children.at(property.to_s).child.content
fm.send(:"#{property}=", value)
rescue => ex
log_err("Could not update property:#{property} - reason #{e.message}")
end
end
不要查看错误消息。查看错误的回溯。然后,您就可以知道它在哪一行失败了。太好了,看起来不错。但是,假设我有一个例子,其中一个对象属性说fm.customerlist=someArray
。我想我必须把它放在它自己的救援区?属性名称也可以更改,这样我就可以得到:fm.description=doc.children.at('descriptionSong').children.content
我结束了让属性看起来像:properties=[“title”=>“title”,“language”=>“language”,“description”=>“descriptionsonsong”]
。你认为有什么更好的解决办法?