Exception Exception Check

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

How can I abstract the exception check in a separate function?

See the example below, thank you for your help!

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 
+4
source share
2 answers

The simplest solution would be to pass your code to the method in the form of a block and go to it in the start / save 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 might want to find a more concise method name than run_code_and_handle_exceptions!

+10
source

In the controllers, I used the rescue_from function. This is pretty DRY:

 class HelloWorldController < ApplicationController rescue_from ActiveRecord::RecordNotFound, :with => :handle_unfound_record def handle_unfound_record # Exception handling... end 
+1
source

All Articles