An error cannot be captured within the map function in Javascript

Imagine having a list of users like the following:

var usersList = [
            { firstName: 'Adam', lastName: 'Yousif', age: 23 },
            { firstName: 'Mohamed', lastName: 'Ali' },
            { firstName: 'Mona', lastName: 'Ahmed', age: 19 },
        ];

Now, you want to use the map function on the usersList to create a modified list as shown below :

var returnList = usersList.map((_user) => {
            var _age;
            try {
                _age = _user.age;
            } catch (error) {
                console.log('An error was caught here : ', error); 
                _age = 'FAILSAFE-VALUE'; 
            }
            var obj = {
                firstName: _user.firstName,
                lastName: _user.lastName,
                age: _age
            }
            return obj;
        });

You have implemented a try-catch block within the map function to replace any undefined "age" property of the second user with 'FAILSAFE-VALUE'. However, it is not functioning correctly.

console.log(returnList);
// prints
// [ 
//     { firstName: 'Adam', lastName: 'Yousif', age: 23 },
//     { firstName: 'Mohamed', lastName: 'Ali', age: undefined }, 
//     { firstName: 'Mona', lastName: 'Ahmed', age: 19 } 
// ]

Is there a way to effectively handle errors within the javascript map function?

Your insights are appreciated.

Answer №1

No try catch is necessary in this case:

usersList.map((_user) => {
            return {
                firstName: _user.firstName,
                lastName: _user.lastName,
                age: _user.age || 'BACKUP-VALUE'
            };
        });

Answer №2

That's because nothing is thrown (the age is just undefined). To get information about this "error" during the map-operation, you can consider the first part of the code snippet provided. If using try-catch is preferred, the second part throws an error 'manually' when _user.age is undefined. This also demonstrates that try-catch does work within a map-operation.

const usersList = [{
    firstName: 'Adam',
    lastName: 'Yousif',
    age: 23
  },
  {
    firstName: 'Mohamed',
    lastName: 'Ali'
  },
  {
    firstName: 'Mona',
    lastName: 'Ahmed',
    age: 19
  },
];

const getFailSafe = user => {
  if (!user.age) {
    console.log(`Note: user.age not available for ${user.firstName} ${user.lastName}`);
    return `FAILSAFE-VALUE`;
  }
  return user.age;
};

// 1. use a warning if .age not present
const returnList = usersList
  .map((_user) => ({
      firstName: _user.firstName,
      lastName: _user.lastName,
      age: getFailSafe(_user)
    })
);

// 2. throw an Error if .age not present
const returnListWithError = usersList
  .map((_user) => {
    let retVal = {
      firstName: _user.firstName,
      lastName: _user.lastName,
    }
    try {
      retVal.age = _user.age || 
        (() => {
          throw new Error(`ERROR: user.age not available for ${
            _user.firstName} ${_user.lastName} (will continue with 'FAILSAFE-VAULE')`);
          })();
    } catch (err) {
      console.log(`${err.message}`);
      retVal.age = `FAILSAFE-VALUE`;
    }
    
    return retVal;
  });

console.log(returnList.find(v => isNaN(v.age)));
console.log(returnListWithError.find(v => isNaN(v.age)));
.as-console-wrapper { top: 0; max-height: 100% !important; }

Answer №3

In that scenario, a try...catch block wouldn't be effective because if you try to access a value that doesn't exist, you'll simply get an undefined.

Here's an alternative approach:

var returnList = usersList.map((_user) => {
    return {
        firstName: _user.firstName,
        lastName: _user.lastName,
        age: _user.age ? _user.age  : 'FAILSAFE-VAULE'
    }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript code in AJAX response functions properly in browsers like Firefox, Chrome, and Opera. However, it encounters issues in Internet Explorer 11, displaying an error message stating

After searching through various posts, I was unable to find a solution to my question. My query involves requesting a jQuery Datepicker via AJAX. I have provided an example for you to review in Firefox, Chrome or Opera: Ajax javascript example Unfortuna ...

Webpack processing causes ES6 script to throw errors

The ES6 script I have works perfectly in modern browsers. However, when I run it through webpack to make it compatible with older browsers, I encounter an issue where the following error appears in my console: Uncaught TypeError: Cannot read property &apo ...

What is the recommended lifecycle hook in Vue.js2 to execute a function when the page is loaded?

I have a dynamic table that can be filled with various numbers of rows, and I want to add an overlay before the data is loaded using my applyOverlay() function. Below is the structure of my HTML: <table id="table" class="datatable" s ...

Utilizing Multi External CDN JavaScript File with Vue CLI Component: A Comprehensive Guide

I've been trying different methods to include external JS files in a Vue Component, such as using mounted() and created(), but unfortunately, none of them have worked for me so far. I'm not sure where I'm going wrong. Any assistance would be ...

Display of undefined data in Ajax success response

After receiving an array object data in the Ajax success result, I am trying to print li tags but they are showing as undefined. This is my Ajax code: $.ajax({ 'method': 'GET', 'url': base_url +'party/sel ...

Having trouble retrieving the value of a custom directive attribute

My custom directive, named "mycomponent", has the following configuration: restrict: 'AE', templateUrl: 'template.html', scope:{ sTransactionType: '=transactionType', sStorageVariable: '=storageVariable&apos ...

Assigning a session variable through a dropdown selection

Currently, I am working on a custom WordPress theme that involves setting a session variable based on the value selected from a dropdown box. This session variable is then used to determine which container should be loaded. The code snippet below shows whe ...

Unexpected token error occurs when making cross-domain AJAX requests to the server and receiving a JSON object

I have set up an express server to handle get requests to specific url endpoints. When responding to these requests, I am sending back data in JSON format to enable making Ajax calls and retrieving data from the page. To allow for cross-domain requests, I ...

Angular confirmation page following successful HTTP POST request to Web API

First question here... I have been given the task of improving an Angular application, even though I am starting with zero experience in Angular. While I do have some background in JavaScript, I mostly work with Java (JSP's and yes, JavaScript). Despi ...

The TypeScript declaration for `gapi.client.storage` is being overlooked

When I call gapi.client.storage.buckets.list(), TypeScript gives me an error saying "Property 'storage' does not exist on type 'typeof client'." This issue is occurring within a Vue.js application where I am utilizing the GAPI library. ...

Tips for adding a numerical prefix to each line when the textarea is in editable mode

After conducting extensive research on Google, I have been unable to find a satisfactory solution. What I am aiming for is similar to the concept illustrated in this image: https://i.sstatic.net/iq6DE.png I should mention that my current technology stack ...

Is there a way to invoke a function within an Angular Service from within the same service itself?

Below is the code snippet I am working with: angular.module('admin') .factory('gridService', ['$resource', 'gridSelectService', 'localStorageService', function ($resource, gridSelectService, ...

Make Angular able to open a new window using window.open instead of opening a popup

Can anyone help me figure out how to use window.open to open a PDF file in a new tab for user download? Below is the Angular 4 code I'm currently using: download() { const data = {html: this.template.toArray()[0].nativeElement.innerHTML}; th ...

Scope Error: Variable 'Undefined' is Not Defined Outside Function in Angular 2

In one of my methods, I am subscribing to an observable and later need to unsubscribe from it in another method. The subCounter() method is triggered from an initialization function and works correctly. subCounter() { this.fml = this.playerService.coun ...

Retrieve the selected checkboxes from the latest .change() trigger

I'm facing an issue with a basic question that I can't seem to find the right terms to research for help. The problem revolves around a .change() listener that monitors checkbox changes within a div (used to toggle Leaflet Map layers). My goal i ...

Checking for the existence of a plugin's function: A comprehensive guide

Here is the code I am working with: $(document).ready(function() { $('.tabs-container').tabs({ tabs: '.bar', tabs_container: '.foo' }); }); Occasionally, the tabs plugin script fails to load, resul ...

Is there a Facebook application embedded in the user's wall?

Is it feasible to create a website similar to YouTube, where users can share it on Facebook and run the app (in this case, the video player) directly on their wall without having to visit the YouTube page? If it is possible, is this functionality limited ...

The jQuery webUI popover does not allow for focusing

Encountering an issue with webUI popover functionality. I have 2 links that each open a popover upon click, and I am trying to copy the contents of both popovers without refreshing the page. When I successfully copy the content from one popover and then tr ...

What is the best way to add an array into another array?

I am working with a main array consisting of 64 positions, and for each position, I need to create another array. For example: someArray[index] = [someObject]. How can I generate these arrays? And how can I access someObject.name and someObject.lastName f ...

Nested JSON array is being shown as [Object Object] within a TextField

I am facing an issue with mapping two sets of JSON data, which I will refer to as Set 1 and Set 2. In Set 1, the data (named sizingData) is being mapped to text fields using the following function: const fillTextField = () => { let result = []; ...