DEV Community

Cover image for Throw a Custom Error in JavaScript

Throw a Custom Error in JavaScript

Kristen Kinnear-Ohlmann on November 22, 2021

In a recent code review, a more senior colleague asked that I throw an error in an exported function so I wasn't just writing a console.log that mi...
Collapse
 
mindplay profile image
Rasmus Schultz

Please always use throw new Error("message...").

For historical reasons, you can throw strings (or anything, really) but it's not considered good form. For one, the Error class has a stacktrace property that gets populated when you throw it. For another, in terms of semantics, a string simply isn't an error - it's just a string; the value itself won't have much meaning to the code that catches it.