为什么console.error是一个方法而不是函数
Why is console.error a method instead of a function?
这些天我大量使用ES6 Promises。因此,如果不指定onRejected
函数,则很容易丢失对异常的跟踪:
new Promise(function(resolve, reject) {
resolve(doCrazyThingThatMightThrowAnException());
}).then(function(result) {
return performDangerousTranformation(result);
});
如果我能使用catch()
添加几个字节,以确保控制台中出现异常,那就太好了:
new Promise(function(resolve, reject) {
resolve(doCrazyThingThatMightThrowAnException());
}).then(function(result) {
return performDangerousTranformation(result);
}).catch(console.error);
不幸的是,这并不起作用,因为console.error
是一个方法而不是一个函数。也就是说,在调用console.error()
时,需要指定接收方console
。您可以在浏览器控制台中很容易地验证这一点:
> console.error('err');
prints err
> var f = console.error;
> f('err');
throws Illegal invocation exception
这意味着添加我的catch()
处理程序有点冗长:
new Promise(function(resolve, reject) {
resolve(doCrazyThingThatMightThrowAnException());
}).then(function(result) {
return performDangerousTranformation(result);
}).catch(function(error) { console.error(error); });
诚然,它在ES6:中要好一点
new Promise(function(resolve, reject) {
resolve(doCrazyThingThatMightThrowAnException());
}).then(function(result) {
return performDangerousTranformation(result);
}).catch((error) => console.error(error));
但最好避免额外的打字。更糟糕的是,如果你今天使用catch(console.error)
,你的异常会被默默地忽略,这正是你试图解决的问题!console.error()
的工作原理有什么基础吗?它需要成为一种方法吗?
节点中的此行为似乎已更改:https://github.com/nodejs/node/commit/025f53c306d91968b292051404aebb8bf2adb458.
如果你的宗教允许,你可以扩展Promise对象:
Promise.prototype.catchLog = function() {
return this.catch(
function(val) {
console.log("Promise has rejected with reason", val);
throw val; // continue with rejected path
}
);
};
然后
function crazy() { throw 99; }
Promise.resolve()
.then(crazy)
.catchLog();
>>> Promise has rejected with reason 99
您要求能够添加"几个字节"的拒绝日志记录;它是catch
末端的三个(L-o-g)。
相关文章:
- 如何在Angular单元测试中从另一个控制器的rootScope将方法添加到rootScope中
- 将一个方法转换为promise:Nodejs
- 如何在所有ng点击事件AngularJS上启动一个方法
- 创建一个方法,通过一个窗口进行迭代并获取Titanium中的所有控件
- 拆散一个大班的巧妙方法
- 如何创建一个方法来验证数组的范围
- 如何将一个方法延迟到另一个方法首先完成,javascript
- Angular2将组件方法导入到另一个组件中
- 你能把一个匿名方法(函数)动态地变成一个命名方法吗
- 在Javascript中对类的每个实例调用一个方法
- 如何重写一个方法,并且仍然能够在重写的方法中使用基方法
- 将其中一个异步方法重写为使用promise的方法
- 添加一个setTimeout方法会使jQuery悬停方法忽略setTimeout方法中的函数
- 一个jquery验证器方法,它不接受纯数字或纯特殊字符,但接受上面是否有字母
- JQuery是否有一个“;移动“;作用或者有没有一种更紧凑的方法来做到这一点
- 我应该返回一个类似console.log()的方法调用吗
- AngularJS从对象中获取另一个值的方法
- JavaScript 方法一个有效,另一个无效
- 正确的删除方法一个属性
- QUnit:每个方法一个测试,每个方法有多个断言或多个测试