Topic 72 of 87
The Error Object
Overview
When a runtime error occurs, JavaScript automatically generates an Error object and passes it to the catch block.
This built-in object contains three crucial properties for debugging: name (the type of error), message (the human-readable description), and stack (the technical stack trace).
Syntax
Inspecting the Error
javascript
try {
// Calling a function that doesn't exist
nonExistentFunction();
} catch (err) {
console.log(err.name); // "ReferenceError"
console.log(err.message); // "nonExistentFunction is not defined"
// The stack trace tells you exactly what line caused it!
console.log(err.stack);
}Built-in Error Types
javascript
// TypeErrors happen when a value is not the expected type
// e.g. calling .toUpperCase() on a number
// ReferenceErrors happen when using an undeclared variable
// SyntaxErrors happen when code is written incorrectly (missing bracket)Common Pitfalls
- Exposing raw
err.messagestrings directly to the user UI. Built-in error messages are often highly technical and confusing to non-developers. You should log the technical error to your server, but display a friendly fallback message to the user.
Interview Questions
Q:
What is the difference between a
TypeError and a ReferenceError?A:
A ReferenceError occurs when you try to access a variable that has not been declared or is out of scope. A TypeError occurs when the variable exists, but you are trying to perform an invalid operation on it (like invoking a string as a function).
Real-World Example
Logging detailed error stack traces to a monitoring service like Sentry so developers can fix bugs remotely.
example
javascript
catch (err) {
Sentry.captureException(err);
showUserFriendlyToast("Something went wrong!");
}Check Your Knowledge
Test your understanding of The Error Object with these quick questions.