JS: Error Constructor
Error constructor
Error(args)-
is equivalent to
new Error(args)console.log(Error("code logic error.")); // Error: code logic error. console.log(new Error("code logic error.")); // Error: code logic error.
new Error()-
return a error object with empty message.
const x = Error(); console.log(x); // Error console.assert(x.message === "");
new Error(message)-
returns a error object
x, wherex.messageis message.const xtext = "code logic error."; const xerr = Error(xtext); console.log(xerr.message === xtext); // true
Link to previous error. the cause argument
cause argument is new in ECMAScript 2022
new Error(message, {cause: errorObj})-
the optional second argument is a data object with string key
"cause".typically is
{cause: errorObj}typically the errorObj is a previous error you are trying to handle.
it allows you to link to an earlier error, so your new error also contains info about what was the root cause.
/* chain error, using the second args { cause: ... } */ const originalError = Error("x not defined."); console.log( Error( "code logic error.", { cause: originalError }, ), ); /* Error: code logic error. at file.js:6:2 { [cause]: Error: x not defined. at file.js:3:23 } */ when you create an error object
xwith cause argument{cause: errObj}, js creates a cause property on the objectx, andx.causeiserrObj.message.const err_x = Error("x not defined."); const err_y = Error("y not defined.", { cause: err_x }); console.assert(err_y.cause === err_x);
Example. chain error in try
/* chain error with { cause: errorObj } */ const xx = undefined; const yy = undefined; try { if (xx === undefined) { throw new Error("xx not defined."); } } catch (xerr) { if (yy === undefined) { throw new Error("yy not defined.", { cause: xerr }); } } /* error: Uncaught Error: yy not defined. throw new Error("yy not defined.", { cause: xerr }); ^ at file.js:12:9 Caused by: Error: xx not defined. at file.js:8:9 */