Fundamental Rules:

  1. Never catch and ignore an exception. You can't just swallow the error and prevent nothing has happened. The exception info should be written into logs or upload to an error reporting server.
  2. In Ruby's exception hierarchy, most application errors fail under StandardError. In general, you do not rescue Exception, you will only need to rescue StandardError and its subclasses.
  3. Return a meaningful message to the client (e.g. API client or Browser) whenever an exception happens. For example, returning 500 for all exceptions is a bad practice.

Below shows an example of exception handling.

First, define an ErrorHandler class. This class handles error by writing to the Rails logger and notify Bugsnag (A cloud error reporting

class ErrorHandler
  def self.handle(error, severity=:error) error.class.to_s error.message error.backtrace.join("\n")
    Bugsnag.notify(error, severity: severity)

When you rescue an exception, you can send the exception to the ErrorHandler:

rescue HTTParty::Error => ex
ErrorHandler.handle(ex) retry = true end

Or, if you are rescue-ing a specific exception at class level:

rescue_from Apipie::ParamError do |e|
  ErrorHandler.handle(e, :info)
  render status: :unprocessable_entity