Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Rescue Exception

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 311
    Comment on it

    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)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: