An exception is an instance of the class Exception or a descendant. In ruby to rescue exceptions we do something like this:
def process_request!
#some code here
rescue
Rails.logger.error { "#{e.message} #{e.backtrace.join("\n")}" }
puts "Exception caught"
end
OR
rescue => e
In both ways we rescue standard errors of exception class and is a good way to handle errors.
However sometimes we make terrible mistake by rescuing Exception like this:
rescue Exception => e
It swallows all type of errors. Exception is the root of the exception class hierarchy in Ruby.
rescue => e is shorthand for rescue StandardError => e
Handling exception globally:
class ApplicationController < ActionController::Base
rescue_from ActiveRecord::RecordNotFound, :with => :handle_exception
def handle_exception
flash[:error] = error.message
redirect_to root_path
end
end
0 Comment(s)