在 JavaScript 中扩展 Error 的好方法是什么? [英] What's a good way to extend Error in JavaScript?
本文介绍了在 JavaScript 中扩展 Error 的好方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在我的 JS 代码中抛出一些东西,我希望它们成为错误的实例,但我也想让它们成为其他东西.
I want to throw some things in my JS code and I want them to be instanceof Error, but I also want to have them be something else.
在 Python 中,通常会继承 Exception.
In Python, typically, one would subclass Exception.
在 JS 中做什么是合适的?
What's the appropriate thing to do in JS?
推荐答案
在 ES6 中:
class MyError extends Error {
constructor(message) {
super(message);
this.name = 'MyError';
}
}
这篇关于在 JavaScript 中扩展 Error 的好方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文