Module: MimeActor::Rescue::ClassMethods

Defined in:
lib/mime_actor/rescue.rb

Instance Method Summary collapse

Instance Method Details

#rescue_act_from(*klazzes, action: nil, format: nil, with: nil, &block) ⇒ Object

Registers a rescue handler for the given error classes with ‘action`/`format` filter

Examples:

Rescue StandardError when raised for any action with ‘html` format

rescue_act_from StandardError, format: :html, with: :handle_html_error

Rescue StandardError when raised for ‘show` action with `json` format

rescue_act_from StandardError, format: :json, action: :show do |ex|
  render status: :bad_request, json: { error: ex.message }
end

Parameters:

  • klazzes

    the error classes to rescue

  • action (defaults to: nil)

    the ‘action` filter

  • format (defaults to: nil)

    the ‘format` filter

  • with (defaults to: nil)

    the rescue handler when ‘block` is not provided

  • block

    the ‘block` to evaluate when `with` is not provided

Raises:

  • (ArgumentError)


46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/mime_actor/rescue.rb', line 46

def rescue_act_from(*klazzes, action: nil, format: nil, with: nil, &block)
  raise ArgumentError, "error filter is required" if klazzes.empty?
  raise ArgumentError, "provide either with: or a block" unless !with.nil? ^ block_given?

  validate!(:callable, with) unless with.nil?
  with = block if block_given?

  validate!(:action_or_actions, action) unless action.nil?
  validate!(:format_or_formats, format) unless format.nil?

  klazzes.each do |klazz|
    validate!(:klazz, klazz)
    error = klazz.is_a?(Module) ? klazz.name : klazz

    # append at the end because strategies are read in reverse.
    actor_rescuers << [error, format, action, with]
  end
end