相关疑难解决方法(0)

抛出字符串而不是错误

既然我们可以throw在Javascript中使用关键字抛出任何内容,那么我们不能直接抛出错误消息字符串吗?

有谁知道这有什么捕获?

让我为此添加一些背景:很多时候,在JavaScript世界中,人们依赖于参数检查而不是使用try-catch机制,所以只抛出致命错误才有意义throw.仍然,为了能够捕获一些系统错误,我必须为我自己的错误使用不同的类,而不是创建Error的子类,我想我应该只使用String.

javascript

64
推荐指数
4
解决办法
2万
查看次数

具有Express的Node.js - 抛出错误vs next(错误)

有人可以在node.js Express应用程序中说明适当的时间来抛出错误,如下所示:

throw new Error('my error');
Run Code Online (Sandbox Code Playgroud)

或者通过回调传递此错误,通常标记为'next',如下所示:

next(error);
Run Code Online (Sandbox Code Playgroud)

你能解释一下他们每个人在Express应用程序环境中会做些什么吗?

例如,这是一个处理URL参数的快速函数:

app.param('lineup_id', function (req, res, next, lineup_id) {
        // typically we might sanity check that user_id is of the right format
        if (lineup_id == null) {
            console.log('null lineup_id');
            req.lineup = null;
            return next(new Error("lineup_id is null"));
        }

        var user_id = app.getMainUser()._id;
        var Lineup = app.mongooseModels.LineupModel.getNewLineup(app.system_db(), user_id);
        Lineup.findById(lineup_id, function (err, lineup) {
            if (err) {
                return next(err);
            }
            if (!lineup) {
                console.log('no lineup matched');
                return next(new Error("no lineup matched"));
            }
            req.lineup = …
Run Code Online (Sandbox Code Playgroud)

node.js express

12
推荐指数
4
解决办法
2万
查看次数

为什么JSON.stringify没有序列化不可枚举的属性?

我正在使用JavaScript将对象序列化为JSON字符串,

我注意到只有可枚举的对象属性被序列化:

var a = Object.create(null,{
  x: { writable:true, configurable:true, value: "hello",enumerable:false },
  y: { writable:true, configurable:true, value: "hello",enumerable:true }
});
document.write(JSON.stringify(a)); //result is {"y":"hello"}
Run Code Online (Sandbox Code Playgroud)

[ ]

我想知道为什么会这样?我搜索了MDN页面,json2解析器文档.我无法在任何地方找到这种行为.

我怀疑这是使用仅通过[[enumerable]]属性的for... in循环的结果(至少在这种情况下).这可以通过类似的东西来完成,同时返回可枚举和不可枚举的属性.这可能是序列化的问题(由于反序列化).json2Object.getOwnPropertyNames

TL;博士

  • 为什么JSON.stringify只序列化可枚举的属性?
  • 这种行为记录在哪里吗?
  • 如何自己实现序列化非可枚举属性?

javascript serialization json

7
推荐指数
1
解决办法
2100
查看次数

`throw 'foo'`、`throw Error('foo')`、`throw new Error('foo')` 和有什么区别?

我见过 3 种在 JavaScript 中抛出错误的不同方式:

throw 'message';
throw Error('message');
throw new Error('message');
Run Code Online (Sandbox Code Playgroud)

它们之间有什么区别?

注意:我知道类似的问题(123等)。它们都没有涵盖所有三种情况。

javascript error-handling throw

6
推荐指数
1
解决办法
1083
查看次数