Lambda API returns 200 on request timeout error

0

I have a login lambda function that is integrated with a API gateway. when the lambda is timed out the status code returned to me is 200 why, and how can I make return 408 instead? { "errorMessage": "##### Task timed out after 3.55 seconds" } And the status code is 200

profile picture
已提問 24 天前檢視次數 139 次
2 個答案
4

When a Lambda function times out, API Gateway will return a 200 HTTP status code by default. This behavior occurs because the Lambda function successfully completed its execution from API Gateway's perspective, even though it might have timed out internally.

To return a different status code, such as 408 for request timeout, you can implement error handling within your Lambda function and explicitly return the desired status code along with the response. Here's how you can modify your Lambda function to return a 408 status code for timeouts:`

def lambda_handler(event, context): try: # Your login logic here # If the operation takes too long and times out, the following line will cause a timeout error # Simulating a timeout error import time time.sleep(5)

    # If login successful, return success response
    return {
        "statusCode": 200,
        "body": "Login successful"
    }
except Exception as e:
    # If an exception occurs, check if it's a timeout error
    if "Task timed out" in str(e):
        # Return 408 status code for request timeout
        return {
            "statusCode": 408,
            "body": "Request timed out"
        }
    else:
        # For other exceptions, return 500 status code
        return {
            "statusCode": 500,
            "body": "Internal server error"
        }

`

已回答 24 天前
1
已接受的答案

Hi

Suggestions: https://aws.amazon.com/blogs/compute/error-handling-patterns-in-amazon-api-gateway-and-aws-lambda/

  • Increase the Lambda timeout if your function genuinely needs more time (up to 15 minutes).
  • Consider asynchronous processing (e.g., SQS queues) for long-running tasks to avoid timeouts altogether.

Map the response status codes for API Gateways:https://repost.aws/knowledge-center/api-gateway-status-codes-http-api

This Video Some More clear to you --> https://www.youtube.com/watch?v=uC2IQwlMJQU

profile picture
專家
GK
已回答 24 天前
profile picture
專家
已審閱 23 天前

您尚未登入。 登入 去張貼答案。

一個好的回答可以清楚地回答問題並提供建設性的意見回饋,同時有助於提問者的專業成長。

回答問題指南