错误处理与重试
为具备弹性的无服务器应用实施完善的错误处理、死信队列和重试机制
错误处理与重试 是 CoddyKit 上的免费 Serverless Backend with AWS Lambda & API Gateway 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Serverless Backend with AWS Lambda & API Gateway 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Serverless Backend with AWS Lambda & API Gateway 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Build Resilient Serverless Apps
In serverless architectures, things can go wrong. Network issues, service outages, or bugs in your code can all lead to failures.
Building resilient applications means they can recover gracefully from these issues, minimizing impact on users and preventing data loss. Error handling and retries are key to this.
Lambda Invocation Types
How Lambda handles errors and retries depends on how your function is invoked. There are two main types:
- Synchronous: The caller waits for a response (e.g., API Gateway, ALB).
- Asynchronous: The caller doesn't wait; Lambda queues the event (e.g., S3, SNS, SQS, EventBridge).
Each type has different retry behaviors by default.
Synchronous Invocation Retries
When a Lambda function is invoked synchronously and returns an error (or times out), Lambda does NOT automatically retry the function.
It's up to the service or client that invoked Lambda (e.g., API Gateway, your mobile app) to implement its own retry logic. Lambda simply passes the error back to the caller.
Asynchronous Invocation Retries
For asynchronous invocations, Lambda has built-in retry mechanisms. If your function fails due to an unhandled error or times out, Lambda will automatically retry the invocation twice.
This means a total of three attempts (initial + two retries) are made, with an exponential backoff between retries. This helps overcome transient issues.
Handling Errors in Code
Beyond Lambda's automatic retries, you should always implement error handling *within* your function code. This allows you to:
- Gracefully manage expected errors (e.g., missing input).
- Log specific details for debugging.
- Return custom error messages to callers.
In Python, the try-except block is your best friend for this.
Python Error Handling Example
This Python Lambda function uses try-except to handle potential KeyError if an expected key is missing, or ZeroDivisionError if a value is zero. Try running it with different inputs!
import json
def lambda_handler(event, context):
try:
# Expecting 'value' key in the event
num = event['value']
result = 100 / num
return {
'statusCode': 200,
'body': json.dumps(f'Result: {result}')
}
except KeyError:
print("Error: 'value' key missing in event.")
return {
'statusCode': 400,
'body': json.dumps('Input Error: Missing \'value\' in event.')
}
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
return {
'statusCode': 400,
'body': json.dumps('Input Error: Cannot divide by zero.')
}
except Exception as e:
print(f"An unexpected error occurred: {e}")
return {
'statusCode': 500,
'body': json.dumps(f'Server Error: {str(e)}')
}
# Example of how to run locally for testing
if __name__ == "__main__":
# Test case 1: Missing key
print("\n--- Test Case 1 (Missing Key) ---")
print(lambda_handler({}, None))
# Test case 2: Zero division
print("\n--- Test Case 2 (Zero Division) ---")
print(lambda_handler({'value': 0}, None))
# Test case 3: Success
print("\n--- Test Case 3 (Success) ---")
print(lambda_handler({'value': 25}, None))
# Test case 4: Non-numeric value (unhandled, falls to generic exception)
print("\n--- Test Case 4 (Type Error) ---")
print(lambda_handler({'value': 'abc'}, None))Dead-Letter Queues (DLQs)
What happens if an asynchronous Lambda invocation fails even after all retries? This is where Dead-Letter Queues (DLQs) come in!
A DLQ is an Amazon SQS queue or SNS topic where Lambda sends events it couldn't process successfully after all retry attempts. It's a crucial mechanism for:
- Preventing data loss.
- Debugging persistent issues.
- Manual reprocessing of failed events.
Configuring a DLQ
To set up a DLQ for your Lambda function:
- Create an SQS queue or SNS topic: This will be your DLQ.
- Grant Permissions: Ensure your Lambda function has permission to publish messages to the chosen SQS queue or SNS topic.
- Configure Lambda: In your Lambda function's configuration (under 'Asynchronous invocation'), specify the ARN of your SQS queue or SNS topic as the DLQ.
This ensures failed events have a safe landing spot.
DLQ Behavior in Action
It's important to understand *when* an event is sent to a DLQ:
- Only for asynchronous invocations.
- After all automatic retry attempts (initial + two retries) have failed.
- If the event's maximum age is exceeded, or the maximum retry attempts are exhausted.
The original event payload, along with some metadata, is sent to the DLQ.
DLQ Understanding
Let's check your understanding of Dead-Letter Queues!
Recap: Error Handling & Retries
You've learned how to make your serverless applications more robust!
- Synchronous vs. Asynchronous: Different invocation types have different default retry behaviors.
- In-code Error Handling: Use
try-exceptto catch and manage errors within your Lambda code. - Dead-Letter Queues (DLQs): A critical mechanism for capturing and inspecting events that fail after all automatic retries, preventing data loss for async invocations.
These practices are essential for building reliable serverless systems!
常见问题解答
「错误处理与重试」课时是免费的吗?
是的 — 「错误处理与重试」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Serverless Backend with AWS Lambda & API Gateway 课程的其余内容,请升级到 CoddyKit PRO。 Serverless Backend with AWS Lambda & API Gateway 课程共包含 4 节课。
「错误处理与重试」这节课中我会学到什么?
为具备弹性的无服务器应用实施完善的错误处理、死信队列和重试机制 你通过在浏览器中直接运行的动手代码来练习 Serverless Backend with AWS Lambda & API Gateway,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Serverless Backend with AWS Lambda & API Gateway 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Serverless Backend with AWS Lambda & API Gateway 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「错误处理与重试」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Serverless Backend with AWS Lambda & API Gateway 课中编写并运行代码吗?
能。每节 Serverless Backend with AWS Lambda & API Gateway 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。