使用Lambda函数返回带有错误信息的JSON格式数据,并将状态码设为4xx,以替代API Gateway默认的200状态码返回。以下是示例代码:
import json
def lambda_handler(event, context):
# your code here
# if error occurs
error_response = {
"statusCode": 400,
"body": json.dumps({"error": "your error message here"})
}
return error_response
# if successful
success_response = {
"statusCode": 200,
"body": json.dumps({"message": "your success message here"})
}
return success_response
在Lambda函数中,如果发生了错误,就返回一个带有错误信息的JSON格式响应,并将状态码设为4xx;如果成功执行,就返回一个带有成功信息的JSON格式响应,并将状态码设为200。最后,将Lambda函数与API Gateway集成即可。