Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwing strings instead of Errors

Tags:

javascript

Since we can throw anything with the throw keyword in Javascript, can't we just throw an error message string directly?

Does anyone know any catch in this?

Let me add some background to this: Very often, in the JavaScript world, people rely on parameter checking as opposed to using the try-catch mechanism, so it makes sense to only throw fatal errors with throw. Still, to be able to catch some system Errors, I have to use a different class for my own errors and instead of creating a subclass of Error, I think I should just use String.

like image 209
billc.cn Avatar asked Jul 16 '12 09:07

billc.cn


People also ask

Can you throw anything in JavaScript?

You Can throw() Anything In JavaScript - And Other async/await Considerations.

Can you throw strings in C++?

An array of chars is often called a string when coding in C. C++ has proper string objects. An exception is thrown until some code catches it. If you do not write code to catch it, nothing will catch it and the program will terminate.

Should you throw errors in JavaScript?

It's best to avoid throwing errors from inside a Promise, because they may not always be caught, depending on how the code that called them is structured. However it's good practice to return an error when rejecting a Promise, and you can return Error custom types just like any other Error.


2 Answers

While it is okay possible to throw any value, it is generally considered poor form to throw anything other than an instance of Error or one of its subclasses. There are several reasons for this:

  1. Catching code may expect the thrown object to have the usual message, stacktrace, and name properties that appear on Errors.
  2. Lack of a stacktrace makes debugging problematic, especially in the case of uncaught exceptions / unhandled rejections. E.g. Debugging an "Uncaught [Object object]" error can be particularly painful.
like image 96
lanzz Avatar answered Oct 06 '22 01:10

lanzz


Yes, you can throw other values, but it's not a good practice.

Does anyone know any catch in this?

A string is not an error object, and does not convey any useful debugging information. Devtools rely on that, such as the file and line where the error was created, the stacktrace at the throw location etc, which are available as properties on Error objects.

Whenever you think of throwing a primitive string value, throw a new Error("<the string>") instead.

like image 31
Bergi Avatar answered Oct 06 '22 00:10

Bergi