如何在 Vue.js 中正确抛出错误?

How to properly throw an error in Vue.js?

我正在构建一个采用不带扩展名的文件名的 SVG 组件。如果使用扩展,我想强制执行此操作并抛出错误。

因为我有一个 ES6 编译器,所以我只是使用这个:

if (this.name.includes('.svg')) {
    throw 'Do not use the svg extension';
}

这是在 Vue.js 中抛出错误的正确方法还是有更好的方法?目前我在实施和测试时收到 2 个警告。

我收到一个 [Vue 警告] 堆栈跟踪和我自己的错误。最好我只想在控制台中抛出一条简单的错误消息来表示用户做错了什么。

关于这种方法的任何想法或在 Vue.js 或一般的 javscript 中更好地处理此问题的技巧?

你应该使用标准的 TypeError:

Creates an instance representing an error that occurs when a variable or parameter is not of a valid type.

throw new TypeError("Do not use the svg extension", filename)

TypeError-MDN

When Error is used like a function -- without new, it will return an Error object. Therefore, a mere call to Error will produce the same output that constructing an Error object via the new keyword would.

throw new Error('Error text.');

Besides the generic Error constructor, there are seven other core error constructors in JavaScript. For client-side exceptions, see Exception handling statements.

EvalError Creates an instance representing an error that occurs regarding the global function eval().

InternalError Creates an instance representing an error that occurs when an internal error in the JavaScript engine is thrown. E.g. "too much recursion".

RangeError Creates an instance representing an error that occurs when a numeric variable or parameter is outside of its valid range. ReferenceError Creates an instance representing an error that occurs when de-referencing an invalid reference.

SyntaxError Creates an instance representing a syntax error that occurs while parsing code in eval().

TypeError Creates an instance representing an error that occurs when a variable or parameter is not of a valid type.

URIError Creates an instance representing an error that occurs when encodeURI() or decodeURI() are passed invalid parameters.