Labs ICT
🎓 SIWES/IT Login

Errors

1 min read | JavaScript Tutorial
🎓

Doing SIWES / IT attachment?

Get a structured training programme, a supervised digital logbook, and a completion certificate with LabsICT SIWES / IT.

Explore SIWES / IT Training

Error Types

JavaScript has built-in error types: Error, SyntaxError, ReferenceError, TypeError, RangeError, and more.

try {
  undefinedVar.name;
} catch (err) {
  console.log(err instanceof ReferenceError); // true
  console.log(err.message);
}

try {
  JSON.parse("not json");
} catch (err) {
  console.log(err instanceof SyntaxError); // true
}

The Error Object

All error types inherit from the Error object, which provides name, message, and stack properties.

try {
  throw new Error("Something went wrong");
} catch (e) {
  console.log("Name:", e.name);
  console.log("Message:", e.message);
  console.log("Stack:", e.stack);
}

Common Built-in Errors

TypeError happens when a value is not the expected type. RangeError occurs when a value is out of range.

try {
  null.length;
} catch (err) {
  console.log("TypeError:", err.message);
}

try {
  new Array(-1);
} catch (err) {
  console.log("RangeError:", err.message);
}