使用 ES6 语法和 Babel 扩展 Javascript 中的错误
Extending Error in Javascript with ES6 syntax & Babel
我正在尝试使用 ES6 和 Babel 扩展错误。没有效果。
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 对象从未获得正确的消息集。
现在我看到了一些关于 SO (for example here) 的解决方案,但它们看起来都非常不符合 ES6-y。如何以一种漂亮的 ES6 方式做到这一点? (在 Babel 中工作)
I am trying to extend Error with ES6
class MyError extends Error {…}
语法正确。
请注意,转译器在从内置对象继承方面仍然存在问题。在你的情况下,
var err = super(m);
Object.assign(this, err);
似乎解决了这个问题。
结合this answer, this answer and this code,我做了这个小的"helper" class,看起来效果不错。
class ExtendableError extends Error {
constructor(message) {
super();
this.message = message;
this.stack = (new Error()).stack;
this.name = this.constructor.name;
}
}
// now I can extend
class MyError extends ExtendableError {
constructor(m) {
super(m);
}
}
var myerror = new MyError("ll");
console.log(myerror.message);
console.log(myerror instanceof Error);
console.log(myerror.name);
console.log(myerror.stack);
根据 Karel Bílek 的回答,我将对 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
。
它还会将错误消息添加到堆栈跟踪中 - 这在 Karel 的示例中是缺失的。
如果可用,它也会使用 captureStackTrace
。
使用 Babel 6,你需要 transform-builtin-extend (npm) 才能正常工作。
class MyError extends Error {
constructor(message) {
super(message);
this.message = message;
this.name = 'MyError';
}
}
There is no need for this.stack = (new Error()).stack;
trick thanks to super()
call.
虽然上述代码无法输出堆栈跟踪,除非在Babel中调用了this.stack = (new Error()).stack;
或Error.captureStackTrace(this, this.constructor.name);
。 IMO,这可能是这里的一个问题。
实际上,堆栈跟踪可以在 Chrome console
和 Node.js v4.2.1
下使用此代码片段输出。
class MyError extends Error{
constructor(msg) {
super(msg);
this.message = msg;
this.name = 'MyError';
}
};
var myerr = new MyError("test");
console.log(myerr.stack);
console.log(myerr);
Chrome console
的输出。
MyError: test
at MyError (<anonymous>:3:28)
at <anonymous>:12:19
at Object.InjectedScript._evaluateOn (<anonymous>:875:140)
at Object.InjectedScript._evaluateAndWrap (<anonymous>:808:34)
at Object.InjectedScript.evaluate (<anonymous>:664:21)
Node.js
的输出
MyError: test
at MyError (/home/bsadmin/test/test.js:5:8)
at Object.<anonymous> (/home/bsadmin/test/test.js:11:13)
at Module._compile (module.js:435:26)
at Object.Module._extensions..js (module.js:442:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:311:12)
at Function.Module.runMain (module.js:467:10)
at startup (node.js:134:18)
at node.js:961:3
除了@zangw 的回答,你还可以这样定义你的错误:
'use strict';
class UserError extends Error {
constructor(msg) {
super(msg);
this.name = this.constructor.name;
}
}
// define errors
class MyError extends UserError {}
class MyOtherError extends UserError {}
console.log(new MyError instanceof Error); // true
throw new MyError('My message');
这将抛出正确的名称、消息和堆栈跟踪:
MyError: My message
at UserError (/Users/honzicek/Projects/api/temp.js:5:10)
at MyError (/Users/honzicek/Projects/api/temp.js:10:1)
at Object.<anonymous> (/Users/honzicek/Projects/api/temp.js:14:7)
at Module._compile (module.js:434:26)
at Object.Module._extensions..js (module.js:452:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:475:10)
at startup (node.js:117:18)
at node.js:951:3
终于平息了。在 Babel 6 中,开发人员 不支持 从内置扩展是明确的。虽然这个技巧 不会 帮助 Map
、Set
等。它确实适用于 Error
。这很重要,因为可以抛出异常的语言的核心思想之一是允许自定义错误。这一点非常重要,因为 Promises 被设计为 reject an Error.
,因此变得更有用。
可悲的事实是,您仍然需要在 ES2015 中以旧方式执行此操作。
自定义错误模式
class MyError {
constructor(message) {
this.name = 'MyError';
this.message = message;
this.stack = new Error().stack; // Optional
}
}
MyError.prototype = Object.create(Error.prototype);
另一方面,Babel 6 有一个插件可以做到这一点。
https://www.npmjs.com/package/babel-plugin-transform-builtin-extend
更新:(截至 2016-09-29)经过一些测试后,babel.io 似乎没有正确说明所有断言(从自定义扩展扩展错误)。但在 Ember.JS 中,扩展错误按预期工作:https://ember-twiddle.com/d88555a6f408174df0a4c8e0fd6b27ce
鉴于此已接受的答案不再有效,您始终可以使用工厂作为替代方案 (repl):
function ErrorFactory(name) {
return class AppError extends Error {
constructor(message) {
super(message);
this.name = name;
this.message = message;
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, this.constructor);
} else {
this.stack = (new Error(message)).stack;
}
}
}
}
// now I can extend
const MyError = ErrorFactory("MyError");
var myerror = new MyError("ll");
console.log(myerror.message);
console.log(myerror instanceof Error);
console.log(myerror.name);
console.log(myerror.stack);
正如@sukima 提到的,您不能扩展原生 JS。无法回答 OP 的问题。
类似于, I did used a factory rather, but followed MDN's recommendation for customer error types。
function extendError(className){
function CustomError(message){
this.name = className;
this.message = message;
this.stack = new Error().stack; // Optional
}
CustomError.prototype = Object.create(Error.prototype);
CustomError.prototype.constructor = CustomError;
return CustomError;
}
中的重大更改
Extending built-ins like Error, Array, and Map may no longer work.
As a recommendation, you can manually adjust the prototype immediately after any super(...) calls.
稍微编辑 Lee Benson 的原始答案对我有用。这还会将 stack
和 ExtendableError
class 的其他方法添加到实例中。
class ExtendableError extends Error {
constructor(message) {
super(message);
Object.setPrototypeOf(this, ExtendableError.prototype);
this.name = this.constructor.name;
}
dump() {
return { message: this.message, stack: this.stack }
}
}
class MyError extends ExtendableError {
constructor(message) {
super(message);
Object.setPrototypeOf(this, MyError.prototype);
}
}
var myerror = new MyError("ll");
console.log(myerror.message);
console.log(myerror.dump());
console.log(myerror instanceof Error);
console.log(myerror.name);
console.log(myerror.stack);
随着 babel 6 的最新变化,我发现 transform-builtin-extend 不再有效。我最终使用了这种混合方法:
export default class MyError {
constructor (message) {
this.name = this.constructor.name;
this.message = message;
this.stack = (new Error(message)).stack;
}
}
MyError.prototype = Object.create(Error.prototype);
MyError.prototype.constructor = MyError;
和
import MyError from './MyError';
export default class MyChildError extends MyError {
constructor (message) {
super(message);
}
}
因此所有这些测试都通过了:
const sut = new MyError('error message');
expect(sut.message).toBe('error message');
expect(sut).toBeInstanceOf(Error);
expect(sut).toBeInstanceOf(MyError);
expect(sut.name).toBe('MyError');
expect(typeof sut.stack).toBe('string');
const sut = new MyChildError('error message');
expect(sut.message).toBe('error message');
expect(sut).toBeInstanceOf(Error);
expect(sut).toBeInstanceOf(MyError);
expect(sut).toBeInstanceOf(MyChildError);
expect(sut.name).toBe('MyChildError');
expect(typeof sut.stack).toBe('string');
不使用 Babel,但在普通 ES6 中,以下内容对我来说似乎工作正常:
class CustomError extends Error {
constructor(...args) {
super(...args);
this.name = this.constructor.name;
}
}
REPL 测试:
> const ce = new CustomError('foobar');
> ce.name
'CustomError'
> ce.message
'foobar'
> ce instanceof CustomError
true
> ce.stack
'CustomError: foobar\n at CustomError (repl:3:1)\n ...'
如您所见,堆栈中同时包含错误名称和消息。我不确定我是否遗漏了什么,但所有其他答案似乎都过于复杂了。
我更喜欢比上面描述的更强大的语法。错误类型的其他方法将帮助您创建漂亮的 console.log
或其他东西。
export class CustomError extends Error {
/**
* @param {string} message
* @param {number} [code = 0]
*/
constructor(message, code = 0) {
super();
/**
* @type {string}
* @readonly
*/
this.message = message;
/**
* @type {number}
* @readonly
*/
this.code = code;
/**
* @type {string}
* @readonly
*/
this.name = this.constructor.name;
/**
* @type {string}
* @readonly
*/
this.stack = CustomError.createStack(this);
}
/**
* @return {string}
*/
toString() {
return this.getPrettyMessage();
}
/**
* @return {string}
*/
getPrettyMessage() {
return `${this.message} Code: ${this.code}.`;
}
/**
* @param {CustomError} error
* @return {string}
* @private
*/
static createStack(error) {
return typeof Error.captureStackTrace === 'function'
? Error.captureStackTrace(error, error.constructor)
: (new Error()).stack;
}
}
要测试此代码,您可以运行类似的东西:
try {
throw new CustomError('Custom error was thrown!');
} catch (e) {
const message = e.getPrettyMessage();
console.warn(message);
}
欢迎扩展 CustomError
类型。可以向扩展类型添加一些特定功能或覆盖现有功能。例如。
export class RequestError extends CustomError {
/**
* @param {string} message
* @param {string} requestUrl
* @param {number} [code = 0]
*/
constructor(message, requestUrl, code = 0) {
super(message, code);
/**
* @type {string}
* @readonly
*/
this.requestUrl = requestUrl;
}
/**
* @return {string}
*/
getPrettyMessage() {
const base = super.getPrettyMessage();
return `${base} Request URL: ${this.requestUrl}.`;
}
}
这对我有用:
/**
* @class AuthorizationError
* @extends {Error}
*/
export class AuthorizationError extends Error {
message = 'UNAUTHORIZED';
name = 'AuthorizationError';
}
我通过这种方式改进了@Lee Benson 的解决方案:
extendableError.js
class ExtendableError extends Error {
constructor(message, errorCode) {
super(message);
this.name = this.constructor.name;
this.errorCode = errorCode
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, this.constructor);
} else {
this.stack = (new Error(message)).stack;
}
}
}
export default ExtendableError
错误示例
import ExtendableError from './ExtendableError'
const AuthorizationErrors = {
NOT_AUTHORIZED: 401,
BAD_PROFILE_TYPE: 402,
ROLE_NOT_ATTRIBUTED: 403
}
class AuthorizationError extends ExtendableError {
static errors = AuthorizationErrors
}
export default AuthorizationError
然后您可以对错误进行分组,同时使用选项说明符来决定在某些应用程序特定情况下采取不同的措施
new AuthorizationError ("The user must be a seller to be able to do a discount", AuthorizationError.errors.BAD_PROFILE_TYPE )
我正在尝试使用 ES6 和 Babel 扩展错误。没有效果。
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 对象从未获得正确的消息集。
现在我看到了一些关于 SO (for example here) 的解决方案,但它们看起来都非常不符合 ES6-y。如何以一种漂亮的 ES6 方式做到这一点? (在 Babel 中工作)
I am trying to extend Error with ES6
class MyError extends Error {…}
语法正确。
请注意,转译器在从内置对象继承方面仍然存在问题。在你的情况下,
var err = super(m);
Object.assign(this, err);
似乎解决了这个问题。
结合this answer, this answer and this code,我做了这个小的"helper" class,看起来效果不错。
class ExtendableError extends Error {
constructor(message) {
super();
this.message = message;
this.stack = (new Error()).stack;
this.name = this.constructor.name;
}
}
// now I can extend
class MyError extends ExtendableError {
constructor(m) {
super(m);
}
}
var myerror = new MyError("ll");
console.log(myerror.message);
console.log(myerror instanceof Error);
console.log(myerror.name);
console.log(myerror.stack);
根据 Karel Bílek 的回答,我将对 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
。
它还会将错误消息添加到堆栈跟踪中 - 这在 Karel 的示例中是缺失的。
如果可用,它也会使用 captureStackTrace
。
使用 Babel 6,你需要 transform-builtin-extend (npm) 才能正常工作。
class MyError extends Error {
constructor(message) {
super(message);
this.message = message;
this.name = 'MyError';
}
}
There is no need for
this.stack = (new Error()).stack;
trick thanks tosuper()
call.
虽然上述代码无法输出堆栈跟踪,除非在Babel中调用了this.stack = (new Error()).stack;
或Error.captureStackTrace(this, this.constructor.name);
。 IMO,这可能是这里的一个问题。
实际上,堆栈跟踪可以在 Chrome console
和 Node.js v4.2.1
下使用此代码片段输出。
class MyError extends Error{
constructor(msg) {
super(msg);
this.message = msg;
this.name = 'MyError';
}
};
var myerr = new MyError("test");
console.log(myerr.stack);
console.log(myerr);
Chrome console
的输出。
MyError: test
at MyError (<anonymous>:3:28)
at <anonymous>:12:19
at Object.InjectedScript._evaluateOn (<anonymous>:875:140)
at Object.InjectedScript._evaluateAndWrap (<anonymous>:808:34)
at Object.InjectedScript.evaluate (<anonymous>:664:21)
Node.js
MyError: test
at MyError (/home/bsadmin/test/test.js:5:8)
at Object.<anonymous> (/home/bsadmin/test/test.js:11:13)
at Module._compile (module.js:435:26)
at Object.Module._extensions..js (module.js:442:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:311:12)
at Function.Module.runMain (module.js:467:10)
at startup (node.js:134:18)
at node.js:961:3
除了@zangw 的回答,你还可以这样定义你的错误:
'use strict';
class UserError extends Error {
constructor(msg) {
super(msg);
this.name = this.constructor.name;
}
}
// define errors
class MyError extends UserError {}
class MyOtherError extends UserError {}
console.log(new MyError instanceof Error); // true
throw new MyError('My message');
这将抛出正确的名称、消息和堆栈跟踪:
MyError: My message
at UserError (/Users/honzicek/Projects/api/temp.js:5:10)
at MyError (/Users/honzicek/Projects/api/temp.js:10:1)
at Object.<anonymous> (/Users/honzicek/Projects/api/temp.js:14:7)
at Module._compile (module.js:434:26)
at Object.Module._extensions..js (module.js:452:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:475:10)
at startup (node.js:117:18)
at node.js:951:3
终于平息了。在 Babel 6 中,开发人员 不支持 从内置扩展是明确的。虽然这个技巧 不会 帮助 Map
、Set
等。它确实适用于 Error
。这很重要,因为可以抛出异常的语言的核心思想之一是允许自定义错误。这一点非常重要,因为 Promises 被设计为 reject an Error.
可悲的事实是,您仍然需要在 ES2015 中以旧方式执行此操作。
自定义错误模式
class MyError {
constructor(message) {
this.name = 'MyError';
this.message = message;
this.stack = new Error().stack; // Optional
}
}
MyError.prototype = Object.create(Error.prototype);
另一方面,Babel 6 有一个插件可以做到这一点。
https://www.npmjs.com/package/babel-plugin-transform-builtin-extend
更新:(截至 2016-09-29)经过一些测试后,babel.io 似乎没有正确说明所有断言(从自定义扩展扩展错误)。但在 Ember.JS 中,扩展错误按预期工作:https://ember-twiddle.com/d88555a6f408174df0a4c8e0fd6b27ce
鉴于此已接受的答案不再有效,您始终可以使用工厂作为替代方案 (repl):
function ErrorFactory(name) {
return class AppError extends Error {
constructor(message) {
super(message);
this.name = name;
this.message = message;
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, this.constructor);
} else {
this.stack = (new Error(message)).stack;
}
}
}
}
// now I can extend
const MyError = ErrorFactory("MyError");
var myerror = new MyError("ll");
console.log(myerror.message);
console.log(myerror instanceof Error);
console.log(myerror.name);
console.log(myerror.stack);
正如@sukima 提到的,您不能扩展原生 JS。无法回答 OP 的问题。
类似于
function extendError(className){
function CustomError(message){
this.name = className;
this.message = message;
this.stack = new Error().stack; // Optional
}
CustomError.prototype = Object.create(Error.prototype);
CustomError.prototype.constructor = CustomError;
return CustomError;
}
Extending built-ins like Error, Array, and Map may no longer work.
As a recommendation, you can manually adjust the prototype immediately after any super(...) calls.
稍微编辑 Lee Benson 的原始答案对我有用。这还会将 stack
和 ExtendableError
class 的其他方法添加到实例中。
class ExtendableError extends Error {
constructor(message) {
super(message);
Object.setPrototypeOf(this, ExtendableError.prototype);
this.name = this.constructor.name;
}
dump() {
return { message: this.message, stack: this.stack }
}
}
class MyError extends ExtendableError {
constructor(message) {
super(message);
Object.setPrototypeOf(this, MyError.prototype);
}
}
var myerror = new MyError("ll");
console.log(myerror.message);
console.log(myerror.dump());
console.log(myerror instanceof Error);
console.log(myerror.name);
console.log(myerror.stack);
随着 babel 6 的最新变化,我发现 transform-builtin-extend 不再有效。我最终使用了这种混合方法:
export default class MyError {
constructor (message) {
this.name = this.constructor.name;
this.message = message;
this.stack = (new Error(message)).stack;
}
}
MyError.prototype = Object.create(Error.prototype);
MyError.prototype.constructor = MyError;
和
import MyError from './MyError';
export default class MyChildError extends MyError {
constructor (message) {
super(message);
}
}
因此所有这些测试都通过了:
const sut = new MyError('error message');
expect(sut.message).toBe('error message');
expect(sut).toBeInstanceOf(Error);
expect(sut).toBeInstanceOf(MyError);
expect(sut.name).toBe('MyError');
expect(typeof sut.stack).toBe('string');
const sut = new MyChildError('error message');
expect(sut.message).toBe('error message');
expect(sut).toBeInstanceOf(Error);
expect(sut).toBeInstanceOf(MyError);
expect(sut).toBeInstanceOf(MyChildError);
expect(sut.name).toBe('MyChildError');
expect(typeof sut.stack).toBe('string');
不使用 Babel,但在普通 ES6 中,以下内容对我来说似乎工作正常:
class CustomError extends Error {
constructor(...args) {
super(...args);
this.name = this.constructor.name;
}
}
REPL 测试:
> const ce = new CustomError('foobar');
> ce.name
'CustomError'
> ce.message
'foobar'
> ce instanceof CustomError
true
> ce.stack
'CustomError: foobar\n at CustomError (repl:3:1)\n ...'
如您所见,堆栈中同时包含错误名称和消息。我不确定我是否遗漏了什么,但所有其他答案似乎都过于复杂了。
我更喜欢比上面描述的更强大的语法。错误类型的其他方法将帮助您创建漂亮的 console.log
或其他东西。
export class CustomError extends Error {
/**
* @param {string} message
* @param {number} [code = 0]
*/
constructor(message, code = 0) {
super();
/**
* @type {string}
* @readonly
*/
this.message = message;
/**
* @type {number}
* @readonly
*/
this.code = code;
/**
* @type {string}
* @readonly
*/
this.name = this.constructor.name;
/**
* @type {string}
* @readonly
*/
this.stack = CustomError.createStack(this);
}
/**
* @return {string}
*/
toString() {
return this.getPrettyMessage();
}
/**
* @return {string}
*/
getPrettyMessage() {
return `${this.message} Code: ${this.code}.`;
}
/**
* @param {CustomError} error
* @return {string}
* @private
*/
static createStack(error) {
return typeof Error.captureStackTrace === 'function'
? Error.captureStackTrace(error, error.constructor)
: (new Error()).stack;
}
}
要测试此代码,您可以运行类似的东西:
try {
throw new CustomError('Custom error was thrown!');
} catch (e) {
const message = e.getPrettyMessage();
console.warn(message);
}
欢迎扩展 CustomError
类型。可以向扩展类型添加一些特定功能或覆盖现有功能。例如。
export class RequestError extends CustomError {
/**
* @param {string} message
* @param {string} requestUrl
* @param {number} [code = 0]
*/
constructor(message, requestUrl, code = 0) {
super(message, code);
/**
* @type {string}
* @readonly
*/
this.requestUrl = requestUrl;
}
/**
* @return {string}
*/
getPrettyMessage() {
const base = super.getPrettyMessage();
return `${base} Request URL: ${this.requestUrl}.`;
}
}
这对我有用:
/**
* @class AuthorizationError
* @extends {Error}
*/
export class AuthorizationError extends Error {
message = 'UNAUTHORIZED';
name = 'AuthorizationError';
}
我通过这种方式改进了@Lee Benson 的解决方案:
extendableError.js
class ExtendableError extends Error {
constructor(message, errorCode) {
super(message);
this.name = this.constructor.name;
this.errorCode = errorCode
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, this.constructor);
} else {
this.stack = (new Error(message)).stack;
}
}
}
export default ExtendableError
错误示例
import ExtendableError from './ExtendableError'
const AuthorizationErrors = {
NOT_AUTHORIZED: 401,
BAD_PROFILE_TYPE: 402,
ROLE_NOT_ATTRIBUTED: 403
}
class AuthorizationError extends ExtendableError {
static errors = AuthorizationErrors
}
export default AuthorizationError
然后您可以对错误进行分组,同时使用选项说明符来决定在某些应用程序特定情况下采取不同的措施
new AuthorizationError ("The user must be a seller to be able to do a discount", AuthorizationError.errors.BAD_PROFILE_TYPE )