Module: Servus::Support::Rescuer::ClassMethods

Defined in:
lib/servus/support/rescuer.rb

Overview

Class methods for rescue_from

Instance Method Summary collapse

Instance Method Details

#rescue_from(*errors, use: Servus::Support::Errors::ServiceError) {|exception| ... } ⇒ Object

Configures automatic error handling for the service.

Declares which exception classes should be automatically rescued and converted to failure responses. Without a block, exceptions are wrapped in the specified ServiceError type with a formatted message including the original exception details.

When a block is provided, it receives the exception and must return either success(data) or failure(message, type:) to create the response.

Examples:

Basic usage with default error type:

class TestService < Servus::Base
  rescue_from Net::HTTPError, Timeout::Error, use: ServiceUnavailableError
end

Custom error handling with block:

class TestService < Servus::Base
  rescue_from ActiveRecord::RecordInvalid do |exception|
    failure("Validation failed: #{exception.message}", type: ValidationError)
  end
end

Recovering from errors with success:

class TestService < Servus::Base
  rescue_from Stripe::CardError do |exception|
    if exception.code == 'card_declined'
      failure("Card declined", type: BadRequestError)
    else
      success(recovered: true, fallback_used: true)
    end
  end
end

Parameters:

  • errors (Class<StandardError>)

    One or more exception classes to rescue from

  • use (Class<Servus::Support::Errors::ServiceError>) (defaults to: Servus::Support::Errors::ServiceError)

    Error class to use when wrapping exceptions (only used without block)

Yields:

  • (exception)

    Optional block for custom error handling

Yield Parameters:

  • exception (StandardError)

    The caught exception

Yield Returns:



125
126
127
128
129
130
131
132
133
134
# File 'lib/servus/support/rescuer.rb', line 125

def rescue_from(*errors, use: Servus::Support::Errors::ServiceError, &block)
  config = {
    errors: errors,
    error_type: use,
    handler: block
  }

  # Add to rescuable_configs array
  self.rescuable_configs = rescuable_configs + [config]
end