使用ES6语法在JavaScript中扩展错误

使用ES6语法在JavaScript中扩展错误

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

问题描述

我正在尝试使用ES6扩展错误。它不工作。

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

var error = new Error(ll);
var myerror = new MyError(ll);
console.log(error.message)//正确显示
console.log(myerror.message)//显示空字符串

错误对象永远不会得到正确的消息集。





现在我已经看到了一些SO的解决方案(),但他们都看起来非常ES6 -y。如何做一个很好的ES6方式? (这是在Babel工作)

解决方案

根据KarelBílek的回答,我会对构造函数

  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))。
}
}
}

//现在我可以扩展

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 而不是通用的错误



它还会将错误消息添加到堆栈跟踪中 - 这是从Karel的例子。



如果可用,它也将使用 captureStackTrace



使用Babel 6,您需要),使其正常工作。


I am trying to extend Error with ES6. 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

The Error object never get the right message set.

Try in Babel REPL.

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)

解决方案

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);

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

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

It will also use captureStackTrace if it's available.

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

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

09-03 05:48