Careeroza
Error Types & Custom Errors
Built-in Error Types
Example
const tests = [
() => undefinedVariable, // ReferenceError
() => null.length, // TypeError
() => new Array(-1), // RangeError
() => JSON.parse("{bad json}"), // SyntaxError
];
for (const t of tests) {
try { t(); } catch (e) { console.log(e.name + ": " + e.message); }
}Output
ReferenceError: undefinedVariable is not defined TypeError: Cannot read properties of null (reading 'length') RangeError: Invalid array length SyntaxError: Expected property name or '}' in JSON at position 1 (line 1 column 2)
Custom Error Classes
Example
Extend Error to describe your own failures, and check them with instanceof:
class ValidationError extends Error {
constructor(field, message) {
super(message);
this.name = "ValidationError";
this.field = field;
}
}
function register(user) {
if (!user.email?.includes("@")) throw new ValidationError("email", "Email is invalid");
return "registered";
}
try {
register({ email: "asha.example.com" });
} catch (e) {
if (e instanceof ValidationError) console.log(`${e.name} on "${e.field}": ${e.message}`);
else throw e; // unknown errors are re-thrown
}Output
ValidationError on "email": Email is invalid
Error Cause
Example
Wrap a low-level error with context using cause:
try {
try {
JSON.parse("{");
} catch (err) {
throw new Error("Could not load settings", { cause: err });
}
} catch (e) {
console.log(e.message, "<-", e.cause.name);
}Output
Could not load settings <- SyntaxError