node.js – AWS X-Ray throws error – Failed to get the current sub/segment from the context

I am experiencing an error after adding code to trace SQS queue integrations and outgoing HTTP/s calls. Below are the code snippets integrated into my project:

// Tracing calls to downstream HTTP web services using the X-Ray SDK for Node.js
// Example app.js - HTTP client (global)
var AWSXRay = require('aws-xray-sdk');
AWSXRay.captureHTTPsGlobal(require('http'));
var http = require('http');
// Tracing AWS SDK calls with the X-Ray SDK for Node.js
// Example sqs-client.js - SQS client instrumentation using SDK for Javascript V3
import { SQSClient } from "@aws-sdk/client-sqs";
const client = new SQSClient({region: 'AWS_REGION'});

CloudWatch is continuously flooded with the following log:

{
  "log": {
    "logtime": "2024-06-06T04:12:45.545+00:00",
    "service": "",
    "env": "",
    "log_type": "ERROR",
    "file": "",
    "message_type": "ERROR",
    "message": "Error: Failed to get the current sub/segment from the context. at Object.contextMissingLogError  as contextMissing  (/usr/src/app/node_modules/aws-xray-sdk-core/dist/lib/context_utils.js:22:27) at Object.getSegment (/usr/src/app/node_modules/aws-xray-sdk-core/dist/lib/context_utils.js:89:53) at Object.resolveSegment (/usr/src/app/node_modules/aws-xray-sdk-core/dist/lib/context_utils.js:71:25) at Object.captureAsyncFunc (/usr/src/app/node_modules/aws-xray-sdk-core/dist/lib/capture.js:48:34) at Timeout._onTimeout (/usr/src/app/server.js:1:1504) at listOnTimeout (node:internal/timers:559:17) at processTimers (node:internal/timers:502:7)"
  }
}

I have tried the following solutions without success:

  • Wrapping the consumer.start() function inside captureFunc.

  • Adding AWSXRay.setContextMissingStrategy("LOG_ERROR") to log only errors.

  • Testing multiple solutions found online.

The project’s npm dependencies include:

Has anyone encountered and resolved a similar issue, or can suggest an alternative method to trace outgoing HTTP/s calls?

Read more here: Source link