Reputation: 766
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.
Upvotes: 2
Views: 2091
Reputation: 16067
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'
})
}
Upvotes: 4
Reputation: 545
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
Upvotes: 0