Tag Archives: rescue

Trusting in Exceptions To Do What They Do

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 of ruby code in a rails controller as an example:

class ArticlesController < ApplicationController
  def show
    @article = Article.find(params[:id])
  end
end

That’s pretty solid, but what happens if someone passes in an ID that does not exist? Well in rails’ production mode, it would return a 404 error

Makes sense! That article doesn’t exist, so it can’t be found. I have dabbled with a little SEO(Search Engine Optimization) and usability and just a 404 isn’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?

Continue reading