Search code examples
javascripterror-handlinges6-promise

'new' operator in Javascript for Error() handling


I am working with Promises and found that when rejecting is recommended to pass an Error() object as argument in order to enable error handling.

I find some examples where a new Error() is given and some others where only Error() is passed.

After testing several cases I just do not find any difference between one usage and other, as seen here where both rejects seem to behave exactly the same:

const p = new Promise((resolve, reject) => {

    setTimeout(reject, 1000, Error("Nope...")); 
    //setTimeout(reject, 1000, new Error("Nope..."));       
});    


p.then(val => { console.log(val) })
.catch(error  => { console.error(error.message) });

In this case, which practical difference is between both error handling ways?


Solution

  • After testing several cases I just do not find any difference between one usage and other...

    That's because when you call Error as a function (without new), it acts exactly like you'd called it with new. That is, Error(x) and new Error(x) do exactly the same thing. This is a "feature" of the Error function. Normally, there's a difference between calling a function without new and calling it with new, just not in this case.

    From the spec:

    The Error constructor:

    • ...
    • ...
    • creates and initializes a new Error object when called as a function rather than as a constructor. Thus the function call Error(…) is equivalent to the object creation expression new Error(…) with the same arguments.
    • ...