CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-sentry--serverless

Official Sentry SDK for various serverless solutions including AWS Lambda and Google Cloud Functions

Pending
Overview
Eval results
Files

aws-lambda.mddocs/

AWS Lambda Integration

Complete AWS Lambda support with handler wrapping, automatic context enhancement, AWS services integration, and performance tracing capabilities specifically designed for the Lambda execution environment.

Capabilities

Initialization

Initialize the Sentry AWS Lambda SDK with platform-specific configurations and integrations.

/**
 * Initializes the Sentry AWS Lambda SDK
 * @param options - Configuration options for the SDK
 */
function init(options?: AWSLambdaOptions): void;

interface AWSLambdaOptions extends NodeOptions {
  /** Internal field that is set to true when init() is called by the Sentry AWS Lambda layer */
  _invokedByLambdaLayer?: boolean;
}

Usage Examples:

import { AWSLambda } from "@sentry/serverless";

// Basic initialization
AWSLambda.init({
  dsn: "your-dsn-here",
});

// With performance tracing
AWSLambda.init({
  dsn: "your-dsn-here",
  tracesSampleRate: 1.0,
  environment: "production",
});

// With custom integrations
AWSLambda.init({
  dsn: "your-dsn-here",
  integrations: [
    // Add custom integrations
  ],
});

Handler Wrapping

Wraps Lambda handlers to add error capture, performance tracing, and automatic context enhancement.

/**
 * Wraps a lambda handler adding it error capture and tracing capabilities
 * @param handler - AWS Lambda handler function
 * @param wrapOptions - Optional configuration for wrapper behavior
 * @returns Wrapped handler with Sentry capabilities
 */
function wrapHandler<TEvent, TResult>(
  handler: Handler<TEvent, TResult>,
  wrapOptions?: Partial<AWSLambdaWrapperOptions>
): Handler<TEvent, TResult>;

// Handler type from AWS Lambda types
type Handler<TEvent = any, TResult = any> = (
  event: TEvent,
  context: Context,
  callback?: Callback<TResult>
) => void | Promise<TResult>;

interface AWSLambdaWrapperOptions {
  /** Timeout for flushing events before Lambda terminates (default: 2000ms) */
  flushTimeout: number;
  /** Whether callback waits for empty event loop (default: false) */
  callbackWaitsForEmptyEventLoop: boolean;
  /** Whether to capture timeout warnings (default: true) */
  captureTimeoutWarning: boolean;
  /** Timeout warning threshold in milliseconds (default: 500) */
  timeoutWarningLimit: number;
  /** Capture all errors when Promise.allSettled is returned (default: false) */
  captureAllSettledReasons: boolean;
  /** Automatically trace all handler invocations (default: true) */
  startTrace: boolean;
}

type AsyncHandler<T extends Handler> = (
  event: Parameters<T>[0],
  context: Parameters<T>[1]
) => Promise<NonNullable<Parameters<Parameters<T>[2]>[1]>>;

Usage Examples:

import { AWSLambda } from "@sentry/serverless";

// Basic async handler wrapping
exports.handler = AWSLambda.wrapHandler(async (event, context) => {
  // Your handler logic
  return { statusCode: 200, body: "Success" };
});

// Sync handler with callback
exports.handler = AWSLambda.wrapHandler((event, context, callback) => {
  // Your handler logic
  callback(null, { statusCode: 200, body: "Success" });
});

// With custom wrapper options
exports.handler = AWSLambda.wrapHandler(async (event, context) => {
  // Handler logic
  return await processEvent(event);
}, {
  flushTimeout: 5000,
  captureTimeoutWarning: true,
  timeoutWarningLimit: 1000,
  captureAllSettledReasons: true
});

// Handle Promise.allSettled patterns
exports.handler = AWSLambda.wrapHandler(async (event, context) => {
  // This will automatically capture errors from rejected promises
  return await Promise.allSettled([
    processItem(event.item1),
    processItem(event.item2),
    processItem(event.item3)
  ]);
}, {
  captureAllSettledReasons: true
});

Auto-Patching

Automatically patch existing Lambda handlers without manual wrapping.

/**
 * Attempts to automatically patch the Lambda handler
 * @param taskRoot - Root directory path where handler is located
 * @param handlerPath - Path to the handler function (e.g., "index.handler")
 */
function tryPatchHandler(taskRoot: string, handlerPath: string): void;

Usage Examples:

import { AWSLambda } from "@sentry/serverless";

// Automatically patch handler based on environment
AWSLambda.tryPatchHandler(process.env.LAMBDA_TASK_ROOT || "/var/task", "index.handler");

Default Integrations

Get the default integrations configured for AWS Lambda environment.

/**
 * Get the default integrations for the AWSLambda SDK
 * @param options - SDK options to configure integrations
 * @returns Array of default integrations including AWS services integration
 */
function getDefaultIntegrations(options: Options): Integration[];

/** @deprecated Use getDefaultIntegrations(options) instead */
const defaultIntegrations: Integration[];

Usage Examples:

import { AWSLambda } from "@sentry/serverless";

// Get default integrations
const integrations = AWSLambda.getDefaultIntegrations({
  // configuration options
});

// Use in custom initialization
AWSLambda.init({
  dsn: "your-dsn-here",
  integrations: [
    ...AWSLambda.getDefaultIntegrations({}),
    // Add additional custom integrations
  ]
});

Context Enhancement

The AWS Lambda integration automatically enhances Sentry scopes with Lambda-specific context:

AWS Lambda Context

// Automatically added to scope
{
  "aws.lambda": {
    "aws_request_id": "8476a536-e9f4-11e8-9739-2dfe598c3fcd",
    "function_name": "myLambdaFunction",
    "function_version": "$LATEST",
    "invoked_function_arn": "arn:aws:lambda:us-west-2:123456789012:function:myLambdaFunction",
    "execution_duration_in_millis": 108.20,
    "remaining_time_in_millis": 691789,
    "sys.argv": ["/var/runtime/bootstrap"]
  }
}

CloudWatch Logs Context

// Automatically added to scope
{
  "aws.cloudwatch.logs": {
    "log_group": "/aws/lambda/myLambdaFunction",
    "log_stream": "2018/11/13/[$LATEST]8bcc747eb4ff4897bf6eba48797c0d73",
    "url": "https://console.aws.amazon.com/cloudwatch/home?region=us-west-2#logsV2:log-groups/..."
  }
}

Layer Integration

Use Sentry's pre-built AWS Lambda layer for simplified deployment:

  1. Add the Sentry Lambda layer to your function
  2. Set environment variables:
    • NODE_OPTIONS: -r @sentry/serverless/build/npm/cjs/awslambda-auto
    • SENTRY_DSN: Your Sentry DSN
    • SENTRY_TRACES_SAMPLE_RATE: Sample rate for performance tracing

The layer automatically initializes Sentry and wraps your handler without code changes.

Error Handling

The Lambda integration provides sophisticated error handling:

  • Automatic Exception Capture: All uncaught exceptions are automatically captured
  • Promise Rejection Handling: Unhandled promise rejections are captured
  • Timeout Warnings: Configurable warnings before Lambda timeout
  • Context Preservation: Lambda context is preserved in error reports
  • Event Flushing: Ensures events are sent before Lambda terminates

Performance Tracing

Automatic performance tracing capabilities:

  • Handler Tracing: Each Lambda invocation is traced as a transaction
  • Distributed Tracing: Continues traces from incoming requests (API Gateway, etc.)
  • AWS Service Calls: Automatically traces AWS SDK calls (when AWS services integration is enabled)
  • Custom Spans: Add custom spans within your handler logic
import { AWSLambda, startSpan } from "@sentry/serverless";

exports.handler = AWSLambda.wrapHandler(async (event, context) => {
  // Custom span within handler
  return await startSpan({ name: "process-event", op: "function" }, async (span) => {
    // Your processing logic
    span.setTag("event-type", event.type);
    return await processEvent(event);
  });
});

Install with Tessl CLI

npx tessl i tessl/npm-sentry--serverless

docs

aws-lambda.md

aws-services.md

core-sentry.md

gcp-functions.md

index.md

tile.json