ES 编码实践 —— 自定义错误

published

使用构造函数(ES5)

function CustomError(message, extra) {
  // Error.captureStackTrace is V8 exclusive, use it like this
  Error.captureStackTrace && Error.captureStackTrace(this, this.constructor);

  this.name =  this.constructor.name;
  this.message = message;

  if (extra) {
    this.extra = extra;
  }
}

require('util').inherits(CustomError, Error);

使用 class(ES2016)

class CustomError extends Error {
  constructor (message, extra) {
    // Calling parent constrcutor of base Error class.
    super(message);

    // Capturing stack trace, excluding constructor call from it.
    Error.captureStackTrace && Error.captureStackTrace(this, this.constructor);

    // Saving class name in the property of our custom error as a shortcut.
    this.name = this.constructor.name;

    if (extra) {
      this.extra = extra;
    }
  }
}