What is the difference between `throw new Error` and `throw someObject`?

What is the difference between `throw new Error` and `throw someObject`?

I want to write a common error handler which will catch custom errors thrown on purpose at any instance of the code.
When I did throw new Error(‘sample’) like in the following code
try {
throw new Error({‘hehe’:’haha’});
// throw new Error(‘hehe’);
} catch(e) {
alert(e);
console.log(e);
}

Log shows in Firefox as Error: [object Object] and I couldn’t parse the object.
For the second throw the log shows as: Error: hehe
Whereas when I did
try {
throw ({‘hehe’:’haha’});
} catch(e) {
alert(e);
console.log(e);
}

the console showed as: Object { hehe=”haha”} in which I was able to access the error properties.
What is the difference?
Is the difference as seen in the code? Like string will be just passed as string and object as objects but the syntax will be different?
I haven’t explored throwing error object… I had done only throwing strings.
Is there any other way than the above two mentioned methods?

Solutions/Answers:

Solution 1:

Here is a good explanation about The Error object and throwing your own errors

The Error Object

Just what we can extract from it in an event of an error? The Error object in all browsers support the following two properties:

  • name: The name of the error, or more specifically, the name of the constructor function the error belongs to.

  • message: A description of the error, with this description varying depending on the browser.

Six possible values can be returned by the name property, which as mentioned correspond to the names of the error’s constructors. They are:

Error Name          Description

EvalError           An error in the eval() function has occurred.

RangeError          Out of range number value has occurred.

ReferenceError      An illegal reference has occurred.

SyntaxError         A syntax error within code inside the eval() function has occurred.
                    All other syntax errors are not caught by try/catch/finally, and will
                    trigger the default browser error message associated with the error. 
                    To catch actual syntax errors, you may use the onerror event.

TypeError           An error in the expected variable type has occurred.

URIError            An error when encoding or decoding the URI has occurred 
                   (ie: when calling encodeURI()).

Throwing your own errors (exceptions)

Instead of waiting for one of the 6 types of errors to occur before control is automatically transferred from the try block to the catch block, you can also explicitly throw your own exceptions to force that to happen on demand. This is great for creating your own definitions of what an error is and when control should be transferred to catch.

Solution 2:

The following article perhaps goes into some more detail as to which is a better choice; throw 'An error' or throw new Error('An error'):

http://www.nczonline.net/blog/2009/03/10/the-art-of-throwing-javascript-errors-part-2/

It suggests that the latter (new Error()) is more reliable, since browsers like Internet Explorer and Safari (unsure of versions) don’t correctly report the message when using the former.

Doing so will cause an error to be thrown, but not all browsers respond the way you’d expect. Firefox, Opera, and Chrome each display an “uncaught exception” message and then include the message string. Safari and Internet Explorer simply throw an “uncaught exception” error and don’t provide the message string at all. Clearly, this is suboptimal from a debugging point of view.

Solution 3:

throw “I’m Evil”

Throw will terminate the further execution & expose message string on catch the error.

try{
    throw 'I\'m Evil'
    console.log('You\'ll never reach to me', 123465)
}
catch(e){
    console.log(e); //I\'m Evil
}

Console after throw will never be reached cause of termination.

throw new Error(“I’m so sweet”)

throw new Error exposes an error event with two params name & message. It also terminate further execution

try{
     throw new Error('I\'m Evil')
     console.log('You\'ll never reach to me', 123465)
}
catch(e){
        console.log(e.name, e.message); //Error, I\'m Evil
}

Solution 4:

You first mention this code:

throw new Error('sample')

and then in your first example you write:

throw new Error({'hehe':'haha'}) 

The first Error object would actually work, because it is expecting a string value, in this case ‘sample’. The second would not because you are trying to pass an object in, and it is expecting a string.

The error object would have the “message” property, which would be ‘sample’.

Solution 5:

you can throw as object

throw ({message: 'This Failed'})

then for example in your try/catch

try {
//
} catch(e) {
    console.log(e); //{message: 'This Failed'}
    console.log(e.message); //This Failed
}

or just throw a string error

throw ('Your error')

try {
//
} catch(e) {
    console.log(e); //Your error
}

throw new Error //only accept a string

Solution 6:

TLDR: they are equivalent.

// this:
const x = Error('I was created using a function call!');
​​​​// has the same functionality as this:
const y = new Error('I was constructed via the "new" keyword!');

source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error