<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Blog - ShiftEleven &#187; exceptions</title>
	<atom:link href="http://shifteleven.com/articles/tag/exceptions/feed" rel="self" type="application/rss+xml" />
	<link>http://shifteleven.com</link>
	<description>Just another WordPress weblog</description>
	<lastBuildDate>Sat, 19 Sep 2009 11:19:15 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0-alpha</generator>
		<item>
		<title>Trusting in Exceptions To Do What They Do</title>
		<link>http://shifteleven.com/articles/2006/12/03/trusting-in-exceptions-to-do-what-they-do</link>
		<comments>http://shifteleven.com/articles/2006/12/03/trusting-in-exceptions-to-do-what-they-do#comments</comments>
		<pubDate>Sun, 03 Dec 2006 23:22:35 +0000</pubDate>
		<dc:creator>K. Adam Christensen</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[ActiveRecord]]></category>
		<category><![CDATA[exceptions]]></category>
		<category><![CDATA[RecordNotFound]]></category>
		<category><![CDATA[rescue]]></category>

		<guid isPermaLink="false">http://dev.fecalrod.com/?p=20</guid>
		<description><![CDATA[Nobody likes to see exceptions when running an application;  it means something went wrong and you should have been on top of it.  But with that, often times I find people will write code to prevent exceptions rather than just allowing them to occur and then using it in their favor.
Take this bit [...]]]></description>
			<content:encoded><![CDATA[<p>Nobody likes to see exceptions when running an application;  it means something went wrong and you should have been on top of it.  But with that, often times I find people will write code to prevent exceptions rather than just allowing them to occur and then using it in their favor.</p>
<p>Take this bit of ruby code in a rails controller as an example:</p>
<pre class="ruby" title="code">class ArticlesController &lt; ApplicationController
  def show
    @article = Article.find(params[:id])
  end
end</pre>
<p>That&#8217;s pretty solid, but what happens if someone passes in an ID that does not exist?  Well in rails&#8217; production mode, it would return a <a href="http://en.wikipedia.org/wiki/404_error.">404 error</a></p>
<p>Makes sense!  That article doesn&#8217;t exist, so it can&#8217;t be found.  I have dabbled with a little SEO(Search Engine Optimization) and usability and just a 404 isn&#8217;t cutting it for me.  I think we can redirect our user back on a right track.  For one, we know the user is trying to read an article, so why not redirect the user to a list of all the articles and give them a little warning?</p>
<p><span id="more-20"></span></p>
<h3>Solution One</h3>
<p>First check that the article exists, and if not, redirect the user to the index page.</p>
<pre class="ruby" title="code">def show
  if Article.exists?(params[:id])
    @article = Article.find(params[:id])
  else
    flash[:error] = 'That article does not exist'
    redirect_to :action =&gt; 'index'
  end
end</pre>
<p>While this works, this requires two queries to our database; one to check it&#8217;s existence and one to load it.  I think there is a better way, and its secret is to go with the flow of the code.</p>
<h3>Solution Two</h3>
<p>One thing<br />
<a href="http://weblog.jamisbuck.org/2006/11/20/under-the-hood-activerecord-base-find-part-2">ActiveRecord::Base#find</a> does do is raise an exception when it cannot find anything, an ActiveRecord::RecordNotFound exception.  We can use this bit of knowledge to re-write that method to something a little simpler by trusting it to throw an exception and then for us to rescue it.</p>
<pre class="ruby" title="code">def show
  @article = Article.find(params[:id])
rescue ActiveRecord::RecordNotFound
  flash[:error] = 'That article does not exist'
  redirect_to :action =&gt; 'index'
end</pre>
<p>One call to the database and fewer lines of code (not a lot, but still).  This time, that nasty little error has been used in our favor; but  one mustn&#8217;t get lazy when using <code>rescue</code> statements.</p>
<h3>Don&#8217;t Get Lazy</h3>
<p>Notice that I used the constant <code>ActiveRecord::RecordNotFound</code> with the statement.  Sure, I could have just written <code>rescue</code>, but that hurts us in two ways.  First, it becomes less readable without it.  Having the <code>RecordNotFound</code> is pretty obvious as to the reason we are executing that statement.  Secondly, it can introduce unwanted side effects.</p>
<pre class="ruby" title="code">def show
  @article = Article.find(params[:id])
  some_illegal_operation
rescue
  flash[:error] = 'That article does not exist'
  redirect_to :action =&gt; 'index'
end</pre>
<p>Whenever that method is called, it will always redirect the user to the index page with that error message.  Because we&#8217;ve rescued all errors, we&#8217;re not getting any notice about how our <code>some_illegal_operation</code> has caused us grief.  This makes debugging and management harder.</p>
<p>The lesson being, don&#8217;t be lazy in those rescues.  Try to avoid a blanket rescue statement if you can.</p>
]]></content:encoded>
			<wfw:commentRss>http://shifteleven.com/articles/2006/12/03/trusting-in-exceptions-to-do-what-they-do/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
