|
| 1 | +# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | + |
| 3 | +class LambdaHandler |
| 4 | + attr_reader :handler_file_name, :handler_method_name |
| 5 | + |
| 6 | + def initialize(env_handler:) |
| 7 | + handler_split = env_handler.split('.') |
| 8 | + if handler_split.size == 2 |
| 9 | + @handler_file_name, @handler_method_name = handler_split |
| 10 | + elsif handler_split.size == 3 |
| 11 | + @handler_file_name, @handler_class, @handler_method_name = handler_split |
| 12 | + else |
| 13 | + raise ArgumentError.new("Invalid handler #{handler_split}, must be of form FILENAME.METHOD or FILENAME.CLASS.METHOD where FILENAME corresponds with an existing Ruby source file FILENAME.rb, CLASS is an optional module/class namespace and METHOD is a callable method. If using CLASS, METHOD must be a class-level method.") |
| 14 | + end |
| 15 | + end |
| 16 | + |
| 17 | + def call_handler(request:, context:) |
| 18 | + begin |
| 19 | + opts = { |
| 20 | + event: request, |
| 21 | + context: context |
| 22 | + } |
| 23 | + if @handler_class |
| 24 | + response = Kernel.const_get(@handler_class).send(@handler_method_name, opts) |
| 25 | + else |
| 26 | + response = __send__(@handler_method_name, opts) |
| 27 | + end |
| 28 | + # serialization can be a part of user code |
| 29 | + response.nil? ? response : AwsLambda::Marshaller.marshall_response(response) |
| 30 | + rescue NoMethodError => e |
| 31 | + # This is a special case of standard error that we want to hard-fail for |
| 32 | + raise LambdaErrors::LambdaHandlerCriticalException.new(e) |
| 33 | + rescue NameError => e |
| 34 | + # This is a special case error that we want to wrap |
| 35 | + raise LambdaErrors::LambdaHandlerCriticalException.new(e) |
| 36 | + rescue StandardError => e |
| 37 | + raise LambdaErrors::LambdaHandlerError.new(e) |
| 38 | + rescue Exception => e |
| 39 | + raise LambdaErrors::LambdaHandlerCriticalException.new(e) |
| 40 | + end |
| 41 | + end |
| 42 | + end |
0 commit comments