[{"data":1,"prerenderedAt":34},["ShallowReactive",2],{"snippet-lambda-function-throwing-errors":3},{"id":4,"title":5,"contributors":6,"description":8,"extension":9,"gitHub":10,"introBox":13,"languages":18,"meta":20,"resources":21,"services":22,"snippets":24,"stem":29,"tags":30,"type":32,"__hash__":33},"snippets\u002Fsnippets\u002Flambda-function-throwing-errors.json","Lambda function with % chance of throwing an error",[7],"content\u002Fcontributors\u002Fjames-beswick.json","The function throws an error based on a % chance provided by an environment variable.","json",{"template":11},{"repoURL":12},"https:\u002F\u002Fgithub.com\u002Faws-samples\u002Fserverless-snippets\u002Ftree\u002Fmain\u002Flambda-function-throwing-errors",{"headline":14,"text":15},"How it works",[16,17],"This snippet creates a Lambda function in Node.js that has a percentage chance of throwing an error. The code uses a Lambda environment variable called CHANCE_OF_FAILURE, which is a value between 0 and 100. If this environment variable is not present, it defaults to 50 (a 50% chance of throwing an error).","This function can be useful for testing failure modes and retry behaviors when consuming events from upstream services.",[19],"Node.js",{},null,[23],"lambda-event-functions",[25],{"title":26,"language":27,"code":28},"Copy the code into Lambda","js","exports.handler = async (event) => {\n    const coinToss = Math.random()*100\n    const failureRate = process.env.CHANCE_OF_FAILURE || 50\n\n    console.log({coinToss, failureRate})\n\n    if ( coinToss \u003C failureRate) {\n      console.error('Error')\n      throw Error(\"There was an error\")\n    } else {\n      return {\n        statusCode: 200,\n        body: JSON.stringify('Hello from Lambda!'),\n      }\n    }\n}","snippets\u002Flambda-function-throwing-errors",[31],"Testing","Integration","tXxht1tNT4uxh1acsfBiv29lC4IdmRl7HbDkosZqPIM",1792578864450]