0
votes

I've written a small lambda function and connected it to the API Gateway. I added an error regex to match .*Error.* and return status 400 in the API Gateway. The problem I face is that the regex seems to match only if the lambda failed, as this thread suggests.

My lambda function:

import logging
import boto3
logger = logging.getLogger()
logger.setLevel(logging.INFO)

def lambda_handler(event, context):
    if int(event['event_id']) == 1:
        return {
            'statusCode': 200,
            "status": "success"
           }
    elif int(event['event_id']) == 2:
        return {
            'statusCode': 400,
            "status": "Error"
           }
    else:
        raise Exception("Error")

It looks like case 1 works well, it returns status 200 by default. With event_id=3 it returns status 400 from the API Gateway (with the stack trace in the data, which I would like to avoid), but with event_id=2 it returns status 200 with the Error string in the data.

How can I mark the lambda as failed without throwing an exception?

1
You can't mark lambda artificially as failed. Any way a function returns cleanly, it is considered as a success.Marcin
@Marcin Thanks. Is there a way to have the api gateway not return status 200 without raising exception in the lambda code?Tomer

1 Answers

0
votes

A failed Lambda means there was some code section in Lambda Function that was failed to be executed. In the current code only the third path has such code section (artificially generated Exception).

It is not possible to execute all your code sections in Lambda and still fail.

If you want to handle API Gateway return status code via program, you'll have to use Lambda Integration. With Lambda integration you may return a response like:

{
    "statusCode": "400",
    body: json.dumps({ "error": "you messed up!" }),
    headers: {
        "Content-Type": "application/json",
    }
}

and you'll get 400 in API response.