Method: Grape::DSL::RequestResponse::ClassMethods#rescue_from

Defined in:
lib/grape/dsl/request_response.rb

#rescue_from(*exception_classes, **options) ⇒ Object

Allows you to rescue certain exceptions that occur to return a grape error rather than raising all the way to the server level.

Examples:

Rescue from custom exceptions

class ExampleAPI < Grape::API
  class CustomError < StandardError; end

  rescue_from CustomError
end

Parameters:

  • exception_classes (Array)

    A list of classes that you want to rescue, or the symbol :all to rescue from all exceptions.

  • block (Block)

    Execution block to handle the given exception.

  • options (Hash)

    Options for the rescue usage.

  • handler (Proc)

    Execution proc to handle the given exception as an alternative to passing a block.

Options Hash (**options):

  • :backtrace (Boolean)

    Include a backtrace in the rescue response.

  • :rescue_subclasses (Boolean)

    Also rescue subclasses of exception classes



100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/grape/dsl/request_response.rb', line 100

def rescue_from(*args, &block)
  if args.last.is_a?(Proc)
    handler = args.pop
  elsif block_given?
    handler = block
  end

  options = args.extract_options!
  if block_given? && options.key?(:with)
    raise ArgumentError, 'both :with option and block cannot be passed'
  end
  handler ||= extract_with(options)

  if args.include?(:all)
    namespace_inheritable(:rescue_all, true)
    namespace_inheritable :all_rescue_handler, handler
  elsif args.include?(:grape_exceptions)
    namespace_inheritable(:rescue_all, true)
    namespace_inheritable(:rescue_grape_exceptions, true)
  else
    handler_type =
      case options[:rescue_subclasses]
      when nil, true
        :rescue_handlers
      else
        :base_only_rescue_handlers
      end

    namespace_reverse_stackable handler_type, Hash[args.map { |arg| [arg, handler] }]
  end

  namespace_stackable(:rescue_options, options)
end