最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript Can't catch an error inside map function - Stack Overflow

programmeradmin3浏览0评论

let's say I have a usersList like this:

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

Now I want to call the map function on usersList and return a modified list like so :

var returnList = usersList.map((_user) => {
            var _age;
            try {
                _age = _user.age;
            } catch (error) {
                console.log('I caught error here : ', error); // <-- not printed
                _age = 'FAILSAFE-VAULE'; // <-- not set
            }
            var obj = {
                firstName: _user.firstName,
                lastName: _user.lastName,
                age: _age
            }
            return obj;
        });

I have a try-catch block inside the map function, the purpose of it is to replace the undefined property "age" of the second user with a 'FAILSAFE-VALUE'. but it doesn't work as should.

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

How to catch an error inside the javascript map function?

Thank you

let's say I have a usersList like this:

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

Now I want to call the map function on usersList and return a modified list like so :

var returnList = usersList.map((_user) => {
            var _age;
            try {
                _age = _user.age;
            } catch (error) {
                console.log('I caught error here : ', error); // <-- not printed
                _age = 'FAILSAFE-VAULE'; // <-- not set
            }
            var obj = {
                firstName: _user.firstName,
                lastName: _user.lastName,
                age: _age
            }
            return obj;
        });

I have a try-catch block inside the map function, the purpose of it is to replace the undefined property "age" of the second user with a 'FAILSAFE-VALUE'. but it doesn't work as should.

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

How to catch an error inside the javascript map function?

Thank you

Share Improve this question edited Oct 22, 2023 at 12:16 Rami Mohamed asked Mar 4, 2020 at 9:41 Rami MohamedRami Mohamed 2,7556 gold badges29 silver badges35 bronze badges 3
  • I dont think you should be try and catching in map... – EugenSunic Commented Mar 4, 2020 at 9:45
  • You're assigning age = 'FAILSAFE-VAULE'; but never using age? Change age: _user.age to age: age – amcquaid Commented Mar 4, 2020 at 9:45
  • You are right @amcquaid . I edited the question. It should make sense now. Thank you – Rami Mohamed Commented Mar 4, 2020 at 9:52
Add a ment  | 

3 Answers 3

Reset to default 9

You don't need to do try catch for that:

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

That's because nothing is thrown (the age is just undefined). If you want information about this "error" during the map-operation, the first part of the snippet may be an idea. If you really want to use try - catch, use the second part (it throws 'manually' when _user.age is undefined). The latter demonstrates (by the way) 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-VAULE`;
  }
  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-VAULE`;
    }
    
    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; }

try...catch block would not work there as after accessing a value which does not exist you just receive an undefined

just do it next way:

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

评论列表(0)

  1. 暂无评论