Copyright © tutorialspoint.com

# Ruby on Rails 2.1 - Exception Handling

The execution and the exception always go together. If you are opening a file which does not exist then if you did not handle this situation properly then your program is considered to be of bad quality.

The program stops if an exception occurs. So 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 the same as the type of the currently thrown exception, or is a superclass of that exception.

# Where to log errors ?

There are three option you have 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. Following 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

You can 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 -%>

Copyright © tutorialspoint.com