Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error:"Failed to get the current sub/segment from the context" when use AWS X-ray in Lambda with node.js

I am trying to use implement the AWS X-ray into my current project (using Node.js and Serverless framework). I am trying to wire the X-ray to one of my lambda function, I got the problem of

Error: Failed to get the current sub/segment from the context.
    at Object.contextMissingRuntimeError [as contextMissing] (/.../node_modules/aws-xray-sdk-core/lib/context_utils.js:21:15)
    at Object.getSegment (/.../node_modules/aws-xray-sdk-core/lib/context_utils.js:92:45)
    at Object.resolveSegment (/.../node_modules/aws-xray-sdk-core/lib/context_utils.js:73:19).....

code below:

import { DynamoDB } from "aws-sdk";
import AWSXRay from 'aws-xray-sdk';

export const handler = async (event, context, callback) => {

    const dynamo = new DynamoDB.DocumentClient({
        service: new DynamoDB({ region })
    });

    AWSXRay.captureAWSClient(dynamo.service);

    try {
        // call dynamoDB function 
    } catch(err) {
        //...
    }
}

for this problem, I use the solution from https://forums.aws.amazon.com/thread.jspa?messageID=821510&#821510

the other solution I tried is from https://forums.aws.amazon.com/thread.jspa?messageID=829923&#829923

code is like

import AWSXRay from 'aws-xray-sdk';
const AWS = AWSXRay.captureAWS(require('aws-sdk'));

export const handler = async (event, context, callback) => {

    const dynamo = new AWS.DynamoDB.DocumentClient({region});

    //....
}

Still not working...

Appreciated to the help of any kind.

like image 679
pyy Avatar asked Nov 29 '18 19:11

pyy


1 Answers

As you mention, that happened because you're running locally (using serverless-offline plugin) and the serverless-offline plugin doesn't provide a valid XRAY context.

One possible way to pass this error and still be able to call your function locally is setting AWS_XRAY_CONTEXT_MISSING environment variable to LOG_ERROR instead of RUNTIME_ERROR (default).

Something like:

serverless invoke local -f functionName -e AWS_XRAY_CONTEXT_MISSING=LOG_ERROR

I didn't test this using serverless framework but it worked when the same error occurred calling an amplify function locally:

amplify function invoke <function-name>
like image 56
r.pedrosa Avatar answered Oct 05 '22 22:10

r.pedrosa