Javascript无法在 map 函数中捕获错误

标签 javascript error-handling try-catch undefined

假设我有一个这样的用户列表:

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

现在我想在 usersList 上调用 map 函数并返回一个修改后的列表,如下所示:
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;
        });

我在 map 函数中有一个 try-catch block ,目的是用 'FAILSAFE-VALUE' 替换第二个用户的未定义属性“age”。 .但它不能正常工作。
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 } 
// ]

如何在 javascript map 函数中捕获错误?

谢谢

最佳答案

您不需要为此 try catch :

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

关于Javascript无法在 map 函数中捕获错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60523070/

相关文章:

java - 如何将 "throw exception"添加到此代码?

javascript - 优酷英文搜索JS API

error-handling - SBCL:在 COMPILE 期间缺少 CONTINUE 重新启动? (真的是:在 HANDLER-CASE 中不存在)

angular - 如何正确捕获@ngrx/effects 错误?

Spring 如何处理 Restful API 的 "Request method POST not supported"错误

perl - 在Try::Tiny catch block 中使用next处理错误

javascript - jQuery-在动画 div 中的图像源之间动态切换

javascript - ng-repeat 表中的 Angularjs 复选框

javascript - 等价于 .show() - 纯 JavaScript 中的 jQuery

c++ - 从 catch (...) C++ 获取异常对象地址