JS: Error (class)
What is error object
Error object is designed as info box for errors. when a program error occurs, may it be syntax error, runtime error, it is represented by an error object.
you can “throw” error by throw statement.
Uncaught error
if you throw an error not in try statement, it's “uncaught error”.
uncaught error aborts the program abruptly.
if (true) { throw new Error("color not defined."); } // error: Uncaught Error: color not defined. // this is never printed, because the program is aborted. console.log("done");
Throw error in try statement
you should throw error in a try statement.
try { if (true) { throw new Error("color not defined."); } } catch (err) { console.log(err); } // Error: color not defined. console.log("done"); // done
Constructor
Properties
lengthnameprototypecaptureStackTraceisErrorstackTraceLimit
console.log( Reflect.ownKeys( Error, ), ); /* [ "length", "name", "prototype", "captureStackTrace", "isError", "stackTraceLimit", ] */
console.assert(Error.length === 1); console.assert(Error.stackTraceLimit === 10); console.assert(Error.name === "Error"); console.log(Error.prototype); // {} console.log(Error.captureStackTrace); // [Function: captureStackTrace] console.log(Error.isError); // [Function: isError]
Error.isError
Error.prototype
Error subclasses
SyntaxErrorTypeErrorRangeErrorReferenceErrorAggregateError→ Multiple errors (used by Promise.any). New in ECMAScript 2021.EvalErrorURIError
console.assert(Error.isPrototypeOf(SyntaxError)); console.assert(Error.isPrototypeOf(RangeError)); console.assert(Error.isPrototypeOf(ReferenceError)); console.assert(Error.isPrototypeOf(AggregateError)); console.assert(Error.isPrototypeOf(EvalError)); console.assert(Error.isPrototypeOf(URIError));
Instance properties
stackmessage→ exist only if constructor is called with an arg.cause→ exist only if constructor is called with second arg. new in ECMAScript 2022.
// error without message only has property key stack console.log(Reflect.ownKeys(Error())); // [ "stack" ]
// if a error has an argument. it also has a message property. console.log( Reflect.ownKeys( Error("abc"), ), ); // [ "stack", "message" ]
// if a error has cause argument. it also has a cause property. const xx = new Error("error xx"); const yy = new Error("error yy", { cause: xx }); console.log(Reflect.ownKeys(yy)); // [ "stack", "message", "cause" ]
const xx = new Error("bad xx"); const yy = new Error("bad yy", { cause: xx }); // show instance properties console.log(Reflect.ownKeys(yy)); // [ "stack", "message", "cause" ] // s------------------------------ console.assert(typeof yy.stack === "string"); console.log(yy.stack); /* Error: bad yy at file.js:3:12 bad yy */ // s------------------------------ console.assert(yy.message === "bad yy"); // s------------------------------ console.log(yy.cause); /* Error: bad xx at file.js:2:12 */