Robert
Robert

Reputation: 41

Ruby - Error Handling - Good Practices

This is more of an opinion oriented question. When handling exceptions in nested codes such as:

Where would you put the exception and error logging? Would you define it on the initialization of the job class in the calling class, which will handle then exception in the job execution or on both levels ?

Upvotes: 1

Views: 1313

Answers (2)

RyanWilcox
RyanWilcox

Reputation: 13974

Probably the best answer, in general, for handling Exceptions in Ruby is reading Exceptional Ruby. It may change your perspective on error handling.

Having said that, your specific case. When I hear "job" in hear "background process", so I'll base my answer on that.

Your job will want to report status while it's doing it's thing. This could be states like "in queue", "running", "finished", but it also could be more informative (user facing) information: "processing first 100 out of 1000 records".

So, if an error happens in your background process, my suggestion is two-fold:

  1. Make sure you catch exceptions before you exit the job. Your background job processor might not like a random exception coming from your code. I, personally, like the idea of catching the exception and saving it to the database, for easy retrieval later. Then again, depending on your background job processor, maybe it handles error reporting for you. (I think reque does, for example).

  2. On the front end, use AJAX (or something) to occasionally check in to how the job is doing. Say every 10 seconds or something. In additional to getting the status of the job, also make sure you return this additional information to the user (if appropriate).

Upvotes: 1

c0deNinja
c0deNinja

Reputation: 3986

if the job handles exceptions then you don't need to wrap the call to the job in a try catch.

but the class that initializes and runs the job could throw exceptions, so you should handle exceptions at that level as well.

here is an example:

def some_job
   begin
     # a bunch of logic
   rescue
     # handle exception
     # log it 
   end
end

it wouldn't make sense then to do this:

def some_manager
  begin
    some_job
  rescue
    # log 
  end
end

but something like this makes more sense:

def some_manager
  begin
    # a bunch of logic
    some_job
    # some more logic
  rescue
    # handle exception
    # log 
  end
end

and of course you would want to catch specific exceptions.

Upvotes: 1

Related Questions