简体   繁体   中英

AWS Lambda Proxy raising exceptions

I am writing an AWS Lambda Python 3.6 function to use as a Lambda proxy on my API in API Gateway. When writing the Lambda, I am calling a helper function, where if there is an error, raises an exception. API Gateway doesn't like this, as it expects "body," "statusCode," and "headers" in the response from the Lambda, and when an exception is raised in Python, those keys are not provided.

I am wondering if it's possible to raise my custom exception with Lambda proxy in mind, so that I can break out of whatever callee I am in and return from the program fluidly, without having to check for errors from the callee in the caller. Basically, I want to raise an exception, provide my status code, headers, and body, and completely return from the Lambda function with API Gateway recognizing the error.

If you're using Lambda Proxy integration, you are responsible for returning a proper response whether its a success or an exception.

You can do so by catching the exception.

def handler(event, context):
    try:
        return {
            'statusCode': 200,
            'body': json.dumps({
                'hello': 'world'
            })
        }
    except BadRequestError:
        return {
            'statusCode': 400,
            'body': json.dumps({
                'error': 'Bad Request Error'
            })
        }
    except:
        return {
            'statusCode': 500,
            'body': json.dumps({
                'error': 'Internal Server Error'
            })
        }

in node.js you can use:

callback(null, RESPONSE_NO_SUCCESS);

where RESPONSE_NO_SUCCESS is like this:

import json
return {
  statusCode: 200,
  body: json.dumps({YOUR_ERROR_HERE})
};

This should work as you want you just need to look up how the callback works in python

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM