使用 ES6 语法扩展 Javascript 中的错误 &通天塔 [英] Extending Error in Javascript with ES6 syntax & Babel

查看:12
本文介绍了使用 ES6 语法扩展 Javascript 中的错误 &通天塔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 ES6 和 Babel 扩展 Error.行不通.

I am trying to extend Error with ES6 and Babel. It isn't working out.

class MyError extends Error {
  constructor(m) {
    super(m);
  }
}

var error = new Error("ll");
var myerror = new MyError("ll");
console.log(error.message) //shows up correctly
console.log(myerror.message) //shows empty string

Error 对象永远不会得到正确的消息集.

The Error object never get the right message set.

试试 Babel REPL.

现在我已经看到了一些关于 SO (例如这里),但它们看起来都非常不符合 ES6 标准.如何以一种不错的 ES6 方式做到这一点?(这是在 Babel 中工作的)

Now I have seen a few solutions on SO (for example here), but they all seem very un-ES6-y. How to do it in a nice, ES6 way? (That is working in Babel)

推荐答案

根据 Karel Bílek 的回答,我会对 constructor 做一个小改动:

Based on Karel Bílek's answer, I'd make a small change to the constructor:

class ExtendableError extends Error {
  constructor(message) {
    super(message);
    this.name = this.constructor.name;
    if (typeof Error.captureStackTrace === 'function') {
      Error.captureStackTrace(this, this.constructor);
    } else { 
      this.stack = (new Error(message)).stack; 
    }
  }
}    

// now I can extend

class MyError extends ExtendableError {}

var myerror = new MyError("ll");
console.log(myerror.message);
console.log(myerror instanceof Error);
console.log(myerror.name);
console.log(myerror.stack);

这将在堆栈中打印MyError,而不是一般的Error.

This will print MyError in the stack, and not the generic Error.

它还会将错误消息添加到堆栈跟踪中——这是 Karel 的示例中缺少的.

It will also add the error message to the stack trace - which was missing from Karel's example.

如果可用,它也会使用 captureStackTrace.

It will also use captureStackTrace if it's available.

使用 Babel 6,您需要 transform-b​​uiltin-extend (npm) 使其工作.

With Babel 6, you need transform-builtin-extend (npm) for this to work.

这篇关于使用 ES6 语法扩展 Javascript 中的错误 &通天塔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆