<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: begin code</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Sun, 18 May 2008 01:47:55 GMT</pubDate>
    <description>DZone Snippets: begin code</description>
    <item>
      <title>Adding helpful error messages to your Ruby code</title>
      <link>http://snippets.dzone.com/posts/show/5446</link>
      <description>This Ruby code raises an error if the XPath query fails because the attribute being queried did not exist for the given element. &lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;  def map_pattr(node, fieldx, valuex)&lt;br /&gt;    begin&lt;br /&gt;    parameter = node.root.elements["parameter[@field='#{fieldx}']"]&lt;br /&gt;    parameter.add_attribute('value', valuex)&lt;br /&gt;    parameter&lt;br /&gt;    &lt;br /&gt;    rescue&lt;br /&gt;      puts 'feedpopulated.rb: map_attr() the field ' + fieldx + ' was not found in params.'&lt;br /&gt;      raise&lt;br /&gt;    end&lt;br /&gt;  end&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;Notice that a raise statement is used to ensure that the system error message is raised and any further code execution is halted.&lt;br /&gt;&lt;br /&gt;Without adding a customized helpful message I would be left scratching my head trying to work out what the following system error message meant.&lt;br /&gt;&lt;code&gt;&lt;br /&gt;./feedpopulated.rb:27:in `map_pattr': undefined method `add_attribute' for nil:NilClass (NoMethodError)&lt;br /&gt;     from ./feedpopulated.rb:51:in `create_record'&lt;br /&gt;     from ./feedpopulated.rb:49:in `each'&lt;br /&gt;     from ./feedpopulated.rb:49:in `create_record'&lt;br /&gt;     from ./recordx.rb:91:in `call_create'&lt;br /&gt;     from ./s3fileuploader_handler.rb:14:in `call'&lt;br /&gt;     from ./s3fileuploader_handler.rb:40:in `invoke'&lt;br /&gt;     from ./uploadtwitteraudio.rb:22:in `initialize'&lt;br /&gt;     from /usr/lib/ruby/1.8/rexml/element.rb:890:in `each'&lt;br /&gt;     from /usr/lib/ruby/1.8/rexml/xpath.rb:53:in `each'&lt;br /&gt;     from /usr/lib/ruby/1.8/rexml/element.rb:890:in `each'&lt;br /&gt;     from ./uploadtwitteraudio.rb:18:in `initialize'&lt;br /&gt;     from ./uploadtwitteraudio.rb:72:in `new'&lt;br /&gt;     from ./uploadtwitteraudio.rb:72&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Reference: &lt;a href="http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_exceptions.html"&gt;Programming Ruby: The Pragmatic Programmer's Guide - Exceptions, Catch, and Throw&lt;/a&gt; [ruby-doc.org]</description>
      <pubDate>Wed, 30 Apr 2008 11:40:47 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/5446</guid>
      <author>jrobertson (James Robertson)</author>
    </item>
  </channel>
</rss>
