Skip to content

Exception Handling in Tim

mtaylor edited this page Apr 3, 2013 · 29 revisions

Exception/Error handling in Tim

Contributers please follow this guide for handling errors and exceptions in Tim.

Swallowing Exceptions

Swallowing exceptions is generally bad practice, however, there are times when swallowing an exception is a perfectly reasonable thing to do. These scenarios should be infrequent, if you are swallowing a lot of exceptions then it usually means you are not following this guide properly.

When is swallowing exceptions appropriate?

If you are creating a method that expects some exception (or an exception is a valid expectation) then you are safe to catch the exception and not log it (i.e. Swallow it). These scenarios should be infrequent. One example of an appropriate time to swallow could be something like as follows:

def can_connect_to_imagefactory?
  begin
    Tim::TargetImage.find(1)
    true
  rescue ActiveResource::ConnectionError
    false
  rescue => e
    if is_active_resource_error?(e)
      true
    else
      raise new Tim::Imagefactory::Error(e, "Error occurred when attempting imagefactory connection")
      logger.error(e.trace)
    end
  end
end

In the above rather contrived example any ActiveResource error is an acceptable response. This is the expected behaviour:

  • Tim can not connect to the server: In this case we would expect to see an ActiveResource::ConnectionError and so we can return false.
  • Server returns a successful response: In this case the TargetImage is found and a success response is returned from the server. Therefore we can return true
  • ** Server returns a unsuccessful response:** This would result in any of the other ActiveResource errors. This is expected so we can catch it and return true.
  • Some unknown error happens: If this is the case we log, wrap and raise the an appropriate error.
Clone this wiki locally