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?
The throw statement throws a user-defined exception. Execution of the current function will stop (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack. If no catch block exists among caller functions, the program will terminate.
Throwing an exception is as simple as using the "throw" statement. You then specify the Exception object you wish to throw. Every Exception includes a message which is a human-readable error description. It can often be related to problems with user input, server, backend, etc.
Same as in other languages like C# or Java:
throw error
throws 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:
function noWrap() {
try {
var o = {}; o.nonexistingMethod();
} catch (error) {
throw error;
}
}
function wrap() {
try {
var o = {}; o.nonexistingMethod();
} catch (error) {
throw new Error(error);
}
}
Calling noWrap()
produces the following error message:
"TypeError: Object #<Object> has no method 'nonexistingMethod'"
// with error.arguments === ['nonexistingMethod', o]
Calling wrap()
produces the following error message:
"Error: TypeError: Object #<Object> has no method 'nonexistingMethod'"
// with error.arguments === undefined
So, as you can see by using a wrapping Error object we can hide the arguments
of 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 Error
objects. 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:
// No wrapping:
TypeError: Object #<Object> has no method 'nonexistingMethod'
at noWrap (http://fiddle.jshell.net/listochkin/tJzCF/show/:22:23)
at http://fiddle.jshell.net/listochkin/tJzCF/show/:37:5
at http://fiddle.jshell.net/js/lib/mootools-core-1.4.5-nocompat.js:3901:62
at http://fiddle.jshell.net/js/lib/mootools-core-1.4.5-nocompat.js:3915:20
// Wrapping:
Error: TypeError: Object #<Object> has no method 'nonexistingMethod'
at wrap (http://fiddle.jshell.net/listochkin/tJzCF/show/:32:15)
at http://fiddle.jshell.net/listochkin/tJzCF/show/:44:5
at http://fiddle.jshell.net/js/lib/mootools-core-1.4.5-nocompat.js:3901:62
at http://fiddle.jshell.net/js/lib/mootools-core-1.4.5-nocompat.js:3915:20
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With