js的Error除了message带其他自定义参数怎么设置?

throw new Error('message')

还可能要带code,reason等字段,要怎么传过去。


回答:

继承

Error本身就是一个类
先说下其他方案的问题:

  1. 用字符串拼接 new Error("xxxx" + "" + "") 可想而知局限性太大
  2. throw {} 抛出一个对象,没有堆栈

既有堆栈又有各种灵活性,就是自己继承一个自定义Error

class MyError extends Error{

constructor(message, data) {

super(message)

this.data = data

}

}

// 同步

try {

throw new MyError('xx报错了', { age: 12, name: '张三' })

}catch(e) {

e.message // xx报错了

e.data // { age: 12, name: '张三' }

e.stack // .....堆栈

}

// 异步

new Promise((resolve, reject) => {

reject(new MyError('xx报错了', { age: 12, name: '张三' }))

}).catch(e => {

e.message // xx报错了

e.data // { age: 12, name: '张三' }

e.stack // .....堆栈

})

题主就可以new MyError('xxx错误', {code,reason}),获取err.data.code,err.data.reason

上面是公用代码,题主可以按照自己需求封装
比如接受多个参数 new MyError('xxx错误', code, reason)

还有一种Error 不就是对象吗,直接加属性就行了:

throw wrapError('xxxxx', code, reason)

function wrapError(message, code, reason){

const err = new Error('message')

err.code = code

err.reason = reason

return err

}

完整的ts代码:
实测在一些babel转换中es6的class会被转成es5,在继承Error的时候会丢失一些属性,就不能只是简单的上面那种几行代码继承,加了一些修复的属性丢失的代码:

class MyError<T> extends Error {

data: T

constructor(message: string, data?: T) {

super(message)

// 某些经过es6转es5会导致属性丢失

Object.defineProperty(this, 'message', {

configurable: true,

enumerable: false,

value: message,

writable: true

})

Object.defineProperty(this, 'name', {

configurable: true,

enumerable: false,

value: this.constructor.name,

writable: true

})

this.data = data as any

if (Object.prototype.hasOwnProperty.call(Error, 'captureStackTrace')) {

Error.captureStackTrace(this, this.constructor)

} else {

Object.defineProperty(this, 'stack', {

configurable: true,

enumerable: false,

value: new Error(message).stack,

writable: true

})

}

}

}


回答:

你可以抛出具体的对象:

try {

throw {code: '', reason: ''}

}catch(err) {

console.log(err.code, err.reason)

}

如果要用Error可以:

try {

throw new Error(JSON.stringify({code: '', reason: ''}))

}catch(err) {

const res = JSON.parse(err.message)

console.log(res.code, res.reason)

}


回答:

直接:

throw  message + code + reason

不过要保证全是字符串

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Refer...


回答:

比如我这样?

var msg = 'This is error message', code = 0, reason = 'Error reason information'

throw new Error(`${msg}\n code:${code}\n reason:${reason}`)

// Uncaught Error: This is error message

// code:0

// reason:Error reason information


回答:

建议你可以这样处理:

throw new Error({ message: '自定义错误消息', customParam: '自定义参数' });

例如:hrow new Error({ message: message1, code: 'code1',reason : reason1 });当这个Error对象被捕获时,可以通过访问message、code和reason来获取这些自定义参数的值。

或者你也可以深入的了解一下throw new Error:https://segmentfault.com/a/1190000021963886
刚看到楼上的方法,真的强,强烈建议使用楼上的继承方法

以上是 js的Error除了message带其他自定义参数怎么设置? 的全部内容, 来源链接: utcz.com/p/934491.html

回到顶部