Ruby on Rails 2.1 - Exception Handling


Advertisements


Execution and exception always go together. If you are opening a file that does not exist, then you need to handle this situation properly, or your program is considered to be of substandard quality.

The program stops if an exception occurs. Exceptions are used to handle various type of errors, which may occur during a program execution and take appropriate action instead of halting program completely.

Exception handling in Ruby on Rails is similar to exception handling in Ruby. Which means, we enclose the code that could raise an exception in a begin/end block and use rescue clauses to tell Ruby the types of exceptions we want to handle.

Syntax

begin  
   # -  
      rescue OneTypeOfException  
   # -  
      rescue AnotherTypeOfException  
   # -  
   else  
      # Other exceptions
      ensure
   # Always will be executed
end

Everything from begin to rescue is protected. If an exception occurs during the execution of this block of code, control is passed to the block between rescue and end.

For each rescue clause in the begin block, Ruby compares the raised Exception against each of the parameters in turn. The match will succeed if the exception named in the rescue clause is same as the type of the currently thrown exception, or is a superclass of that exception.

Where to Log Errors?

You have three options when an exception is thrown −

  • Log to an internal log file (logger.error)

  • Display an appropriate message to the user

  • Redisplay the original page to continue

The error reporting to the application is done to a structure called a flash. The flash is a hash bucket to contain your message until the next request before being deleted automatically. You can access it with the @flash variable. Given below is the simplest form of using logger module to log error messages in an internal file.

begin
.........
rescue Exception => exc
   logger.error("Message for the log file #{exc.message}")
   flash[:notice] = "Store error message"
   redirect_to(:action => 'index')
end

To display all the messages from @flash in your view or layout (.html.erb), you can add the following −

<% @flash[:notice] -%>
<div id="notice"><%= @flash[:notice] %></div>
<% end -%>


Advertisements