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.
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.
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 endEverything 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.
begin ......... rescue Exception => exc logger.error("Message for the log file #{exc.message}") flash[:notice] = "Store error message" redirect_to(:action => 'index') endYou 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 -%>
No comments:
Post a Comment