Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
421 views
in Technique[技术] by (71.8m points)

javascript - 我可以使用'throw {}'并且堆栈跟踪正确吗?(Can I use 'throw {}' and stack trace is right in promise?)

I tried two way as below(我尝试了以下两种方法)

new Promise((resolve, reject) => { reject() }) .catch(() => { throw { name: 'a', message: 'b' } }) new Promise((resolve, reject) => { reject() }) .catch(() => { throw new Error({ name: 'a', message: 'b' }); }) 在此处输入图片说明 ' throw {} 'have a problem, is stack trace is not right(' throw {} '有问题,堆栈跟踪不正确) stack trace of the ' throw new Error() ' is right, but can't throw message as json(' throw new Error() '的堆栈跟踪是正确的,但是不能将消息作为json抛出) Can I use ' throw {} ' and stack trace is right?(我可以使用' throw {} '并且堆栈跟踪正确吗?)   ask by flyerH translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The stack property only exists on Error objects.(stack属性仅存在于Error对象上。)

The first parameter of the Error constructor is a string though, so if you pass an object to it it'll be stringified.(但是, Error构造函数的第一个参数是字符串,因此,如果将对象传递给它,它将被字符串化。) You could do(你可以做) throw Object.assign(new Error("message"), { // properties }); to throw an error object with custom properties.(抛出带有自定义属性的错误对象。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...