I have the following coffeescript code:
try
do something
catch error
log something
throw error
Should I use throw new Error(error) instead of throw error?
What is the difference?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Same as in other languages like C# or Java:
throw errorthrows the same Error objectthrow new Error(error)wraps it into a new Error object. The later is used, for example, in Java when you need to convert checked Exception into unchecked one. In JavaScript you don’t need to wrap exceptions as this would make stacktrace a bit longer and less pretty.Edit: There’re some security implications as well. Here’s an example:
Calling
noWrap()produces the following error message:Calling
wrap()produces the following error message:So, as you can see by using a wrapping Error object we can hide the
argumentsof original error. Suppose you’re writing one of the following:In all those cases listed above in order to stay secure you should wrap your
Errorobjects. Otherwise you may accidentally leak references to your internal objects, functions and variables.Edit 2: Regarding stacktraces. Both variants preserve them. Here’s a working example and I get the following stacktraces in Chrome: