Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstracting exception checking

I have a range of methods that use the same exception handling.

How can I abstract out the exception checking into a separate function?

See example below, thanks a lot for your help folks!

def a
  code
  begin
    rescue 1...
    rescue 2...
    rescue 3...
    rescue 4...
  end
end

def b
  code
  begin
    rescue 1...
    rescue 2...
    rescue 3...
    rescue 4...
  end
end
like image 309
meow Avatar asked Dec 22 '22 20:12

meow


2 Answers

The simplest solution would be to pass your code to a method as a block and yield to it within a begin/rescue expression:

def run_code_and_handle_exceptions
  begin
    yield
  rescue 1...
  rescue 2...
  rescue 3...
  rescue 4...
  end
end

# Elsewhere...
def a
  run_code_and_handle_exceptions do
    code
  end
end
# etc...

You may want to come up with a more succinct method name than run_code_and_handle_exceptions!

like image 193
Jonathan Avatar answered Jan 08 '23 07:01

Jonathan


In controllers I've used rescue_from -functionality. It's quite DRY:

class HelloWorldController < ApplicationController
  rescue_from ActiveRecord::RecordNotFound, :with => :handle_unfound_record

  def handle_unfound_record
    # Exception handling...
  end
like image 30
hade Avatar answered Jan 08 '23 07:01

hade