JavaScript
Common error types
Recognize common error types like TypeError, RangeError and ReferenceError.
Common error types
In JavaScript the most common error types are TypeError, RangeError, ReferenceError and SyntaxError. Each points to a different programming mistake and they can be told apart in the catch block with e.name.
For example writing null.foo gives a TypeError, using an undefined variable gives a ReferenceError. An invalid length like Array(-1) gives a RangeError. SyntaxError is thrown when the code has a syntax mistake and is usually caught before running.
Telling error types apart
Telling error types apart lets you do different work in the catch block. You can check the type with the instanceof operator or by comparing e.name. For example if (e instanceof TypeError) catches only type errors.
This is especially useful when you want to customize the message shown to the user based on the error type. You can show "Undefined variable" for a ReferenceError or "Invalid range" for a RangeError. This way the application gives clearer error feedback.
Exercise Show a message based on error type
Define a function called handleError. It should take an e parameter. In the body check with if (e instanceof TypeError); when it holds call console.error("Type error:", e.message). With else if (e instanceof RangeError) also call console.error("Range error:", e.message). Then call this function as try { null.foo; } catch (e) { handleError(e); }.
Show example solution
function handleError(e) {
if (e instanceof TypeError) {
console.error("Type error:", e.message);
} else if (e instanceof RangeError) {
console.error("Range error:", e.message);
}
}
try {
null.foo;
} catch (e) {
handleError(e);
}
Test yourself
-
What type of error does null.foo give?
null.foo;
- ReferenceError
- TypeError
- RangeError
- SyntaxError
Show answer
TypeError — Correct. Accessing a property on null gives a TypeError.
-
Identify the error type
try {
console.log(unknownVar);
} catch (e) {
if (e instanceof ____) {
console.log("Undefined variable");
}
}
Show answer
try {
console.log(unknownVar);
} catch (e) {
if (e instanceof ReferenceError) {
console.log("Undefined variable");
}
}
-
Match error types to their cause
- TypeError
- Wrong type usage
- RangeError
- Invalid range
- ReferenceError
- Undefined variable
- SyntaxError
- Syntax mistake
Next lesson: Summary - Errors