Errors in JavaScript
Errors are objects in js, which are thrown when runtime error occurs. The error can also be a base object for user defined exceptions.
Runtime errors result in new Error, objects being created and thrown.
Serializable object
A seriziable objects is one which can be serialized and later deserialized in any JS environment. For example: be stored on disk and later restored, or cloned with structuredClone(), or shared between workers.
Serialization may not include all properties of original object, eg: a serialization of a DOMException must include the name and message property, but will it include other properties is dependent on the implementation.
As a result a deserialized object may not be an identical clone/copy of original object, but it will be a deep copy. So any property that is serialized and then deserialized into new object will share no references with the original object.
StructuredClone()
The Structured clone is a window interface creates deep copy of a given value using the structured clone algorithm.
structuredClone(value) // object to be cloned, can be any structured-cloneable type.
structuredClone(value, options) // An array of transferable objects that will be moved rather than cloned to the returned object
// Create an object with a value and a circular reference to itself.
const original = { name: "MDN" };
original.itself = original;
// Clone it
const clone = structuredClone(original);
console.assert(clone !== original); // the objects are not the same (not same identity)
console.assert(clone.name === "MDN"); // they do have the same values
console.assert(clone.itself === clone); // and the circular reference is preserved
Error and their different structures in js
Besides the generic Error constructor, there are other core error constructors in JavaScript. For
EvalErrorCreates an instance representing an error that occurs regarding the global function
eval().RangeErrorCreates an instance representing an error that occurs when a numeric variable or parameter is outside its valid range.
ReferenceErrorCreates an instance representing an error that occurs when de-referencing an invalid reference.
SyntaxErrorCreates an instance representing a syntax error.
TypeErrorCreates an instance representing an error that occurs when a variable or parameter is not of a valid type.
URIErrorCreates an instance representing an error that occurs when
encodeURI()ordecodeURI()are passed invalid parameters.AggregateErrorCreates an instance representing several errors wrapped in a single error when multiple errors need to be reported by an operation, for example by
Promise.any().
try {
throw new Error("Whoops!");
} catch (e) {
console.error(`${e.name}: ${e.message}`);
}
Handling a specific type of error
try {
foo.bar();
} catch (e) {
if (e instanceof EvalError) {
console.error(`${e.name}: ${e.message}`);
} else if (e instanceof RangeError) {
console.error(`${e.name}: ${e.message}`);
}
// etc.
else {
// If none of our cases matched leave the Error unhandled
throw e;
}
}
Custom errors in JS
class MyError extends Error {
constructor( message , options ) {
super(message, options)
}
}
console.log(new MyError("test", { cause: new Error("cause") }).cause);
// Error: cause
class CustomError extends Error {
constructor(foo = "bar", ...params) {
super(...params);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, CustomError);
}
this.name = "CustomError";
this.foo = foo;
this.date = new Date();
}
}
try {
throw new CustomError("baz", "bazMessage");
} catch (e) {
console.error(e.name); // CustomError
console.error(e.foo); // baz
console.error(e.message); // bazMessage
console.error(e.stack); // stack trace
}