Skip to content

11 Lambda Errors

DodaTech 1 min read

title: Lambda Error Handling for Serverless APIs weight: 21 date: 2026-06-28 lastmod: 2026-06-28 description: Master Lambda error handling including retry behavior, dead-letter queues, structured error responses for API Gateway, CloudWatch alarms, and error observability. tags: [api-development, serverless]


Lambda error handling manages function failures with automatic retries for async invocations, dead-letter queues (DLQ) for failed events, structured error responses for synchronous API Gateway calls, and CloudWatch alarms for error monitoring.

```python
import json
import traceback

class APIError(Exception):
    def __init__(self, status_code: int, code: str, message: str):
        self.status_code = status_code
        self.code = code
        self.message = message

def lambda_handler(event, context):
    try:
        user_id = event["pathParameters"]["user_id"]
        if not user_id.isdigit():
            raise APIError(400, "INVALID_ID", "User ID must be numeric")

        result = get_user(int(user_id))
        if not result:
            raise APIError(404, "NOT_FOUND", f"User {user_id} not found")

        return api_response(200, result)

    except APIError as e:
        print(f"API Error: {e.code} - {e.message}")
        return api_response(e.status_code, {"code": e.code, "message": e.message})
    except Exception as e:
        print(f"Unexpected error: {traceback.format_exc()}")
        return api_response(500, {"code": "INTERNAL_ERROR", "message": "Something went wrong"})

def api_response(status_code, body):
    return {
        "statusCode": status_code,
        "headers": {"Content-Type": "application/json"},
        "body": json.dumps(body)
    }

What's Next

Now learn about Lambda cold starts in Building Serverless APIs.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro