Lambda function with % chance of throwing an error

The function throws an error based on a % chance provided by an environment variable.

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.

Copy the code into Lambda

exports.handler = async (event) => {
    const coinToss = Math.random()*100
    const failureRate = process.env.CHANCE_OF_FAILURE || 50

    console.log({coinToss, failureRate})

    if ( coinToss < failureRate) {
      console.error('Error')
      throw Error("There was an error")
    } else {
      return {
        statusCode: 200,
        body: JSON.stringify('Hello from Lambda!'),
      }
    }
}
                                


Created by:

James Beswick

James Beswick

I am a self-confessed serverless geek and enjoy helping developers build faster with serverless! I have been software developer and product manager before becoming a Developer Advocate. Ask me anything!

Follow on LinkedIn