简体   繁体   中英

Extending Error with ES6 Class

I'm unable to run any of the methods on this MyError class.

class MyError extends Error {
  constructor(message) {
    super()
    this.name = 'MyError'
    this.message = message
    this.stack = (new Error(message)).stack
    return this
  }
  doSomething () {
    return this.message + " dolphin"
  }
}

let myError = new MyError('Invalid Form.')

console.log(myError.doSomething())

For some reason this is giving me an error:

console.log(myError.doSomething());
                    ^

TypeError: myError.doSomething is not a function

Found out you can't extend Error.

There's a package es6-error with an Error that you can extend.

import ExtendableError from 'es6-error';

class MyError extends ExtendableError {
  constructor(message) {
    super()
    this.name = 'MyError'
    this.message = message
    this.stack = (new Error(message)).stack
    return this
  }
  doSomething () {
    return this.message + " dolphin"
  }
}

let myError = new MyError('Invalid Form.')

console.log(myError.doSomething())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM