Tips for handling errors in lambda functions

Does anyone have any tips for interacting with lambda functions?

For example

  • Do you use any retry logic? (i.e. retry the function in case of failure)?
  • Does your retry logic go in the lambda function or your frontend?

Currently I do this:
Ping the lambda function from the front end
The lambda function has try and catch blocks
Then the front end contains all my retry logic

This approach looks like this:

const fetch = require('node-fetch')

exports.handler = async (event) => {

    // Options
    const options = {
        method: 'PUT',
        url: '',
        headers: {
            // insert headers
        body: JSON.stringify({ /* insert body */ })
    try {
        const response = await fetch(url, options);
        const data = await response.json();
        return {
        statusCode: 200,
        body: JSON.stringify({
            data: data
        headers: {
            // insert headers
    } catch (error) {
        return {
        statusCode: 500,
        body: JSON.stringify({ error: 'Failed fetch inside lambda function' }),
        headers: {
            // insert headers


Then in my frontend:

// fetch() helper that just adds retry logic 
function myFetch(url, options = {}, retries = 3) {

  return fetch(url, options)
    .then(response => {
      if (!response.ok) {
        // retry or throw error
        if (retries > 0) {
          console.log('Fetch failed with code ' + response.status)
          setTimeout(() => {
            return myFetch(url, options, retries - 1)
          }, 1000);
        } else {
          throw new Error(response.status);
      return response
    .catch(error => console.log(error.message))

  .then(response => response.json())
  .then(data => {

This works but it’d be helpful to hear how other people solve this same problem :slightly_smiling_face:

I don’t use any retry logic myself, but if I had to, I’d do it this way:

  • Fetch the function from frontend.
  • Show some error notification on the frontend and let user choose if they wish to retry.
  • If they choose retry, I fetch again or else leave it as it is.

The above won’t be an option if fetching the function is not-optional for the functioning of the website. If this is the case, I’d still send the failure data to the frontend so that I can update the frontend to show that I’m retrying automatically.

In any case, I’d keep the retry logic in frontend for the following reasons:

  1. The serverless function would timeout after 10 seconds anyways.
  2. The user won’t know we’re retrying in the function thus the wait time would be a bad UI. If we give them a choice of retrying, they would know it might take a few more seconds as we’re retrying.

This comes off the top of my head and sure there might be better ideas, but I hope this helps.

1 Like