简体   繁体   中英

How to properly throw an error in Vue.js?

I am building an SVG component that takes a filename without extension. I want to force this and throw an error if the extension is used though.

Since I have a ES6 compiler I am simply using this:

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

Is this a proper way to throw an error in Vue.js or is there a better way? Currently I am getting 2 warnings when I implement this and test it out.

I am getting a [Vue warn] with stacktrace and my own error. Preferably I would just like to throw a simply error message in the console to signify what a user did wrong.

Any thoughts on this approach or tips to handle this better in Vue.js or javscript in general?

You should use the standard 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. Eg "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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM