In Jurassic Park, classifying dinosaurs is critical for safety — you need to know if you're dealing with a gentle Brachiosaurus or a dangerous Velociraptor. Similarly in JavaScript, recognizing different types of errors helps effectively diagnose and solve problems in code.
Dr. Ian Malcolm would say: "Errors... uh... find a way." And indeed, even in the most carefully written code, errors can appear. That's why understanding their types is so important.
SyntaxError is the most basic type of error — it occurs when code contains a construct that violates JavaScript syntax rules. It's like trying to communicate with a dinosaur in the wrong language — it won't work!
1// Examples of syntax errors
2function checkDinosaurEnclosure( { // Missing closing parenthesis
3 return isSecure;
4}
5
6const velociraptorCount = 3;
7if (velociraptorCount > 2) {
8 console.log("Too many raptors!") // Missing semicolon (acceptable in some contexts)
9} else {
10 console.log("Acceptable safety level");
11}JavaScript reports SyntaxError immediately during code parsing, before it executes. Such an error completely prevents the program from running.
ReferenceError appears when you try to access a variable or function that doesn't exist or isn't accessible in the current scope. It's like looking for a dinosaur that escaped its enclosure — it's not where it should be!
1// Examples of ReferenceError
2function alertSecurityTeam() {
3 // tyrannosaurus is not defined in this scope
4 if (tyrannosaurus.isLoose) {
5 sendEmergencyAlert();
6 }
7}
8
9// Using a variable before its declaration
10console.log(securityCode); // ReferenceError
11const securityCode = "1234";TypeError occurs when an operation is performed on a value of the wrong type, or when you try to call a property or method that doesn't exist. It's like trying to treat a herbivorous Triceratops as a predator.
1// Examples of TypeError
2const dinosaurSpecies = ["Tyrannosaurus", "Velociraptor", "Triceratops"];
3
4// Trying to call a method on the wrong type
5dinosaurSpecies.toUpperCase(); // TypeError: dinosaurSpecies.toUpperCase is not a function
6
7// Trying to access a property of undefined
8const securitySystem = null;
9console.log(securitySystem.isActive); // TypeError: Cannot read property 'isActive' of null
10
11// Trying to call a value that is not a function
12const dinoCount = 5;
13dinoCount(); // TypeError: dinoCount is not a functionRangeError appears when a numeric value is outside the allowed range. It's like trying to house more dinosaurs in an enclosure than it can safely hold.
1// Examples of RangeError
2function setDinosaurFeedingSchedule(intervalMs) {
3 // Passing a negative value to setTimeout will cause RangeError
4 setTimeout(feedDinosaurs, intervalMs);
5}
6
7setDinosaurFeedingSchedule(-1000); // RangeError
8
9// Another example — exceeding maximum recursion depth
10function countdownToParkopenning(n) {
11 console.log(n);
12 // No base case causes RangeError: Maximum call stack size exceeded
13 countdownToParkopenning(n - 1);
14}
15
16countdownToParkopenning(10);URIError occurs when invalid parameters are passed to URI encoding or decoding functions. This is a rare error type, but can occur when processing data from APIs.
1// Example of URIError
2try {
3 // Attempting to decode an invalid URI sequence
4 decodeURIComponent('%'); // URIError: Invalid URI
5} catch (error) {
6 console.error("Error decoding enclosure identifier:", error.message);
7}EvalError was historically reported for problems related to the
eval() function, but in modern JavaScript it is rarely used, just as the eval() function should rarely be used for security reasons.AggregateError is a newer error type introduced in ES2020 that groups multiple errors into one. It's used by
Promise.any() when all promises are rejected.1// Example of AggregateError
2const dinosaurHealthChecks = [
3 Promise.reject(new Error("Raptor 1: Elevated temperature")),
4 Promise.reject(new Error("Raptor 2: Abnormal blood parameters")),
5 Promise.reject(new Error("Raptor 3: Refused to cooperate"))
6];
7
8Promise.any(dinosaurHealthChecks).catch(errors => {
9 console.log(errors instanceof AggregateError); // true
10 console.log(errors.message); // "All promises were rejected"
11 console.log(errors.errors); // Array containing all errors
12});InternalError is reported when an internal error occurs in the JavaScript engine, e.g. too much recursion. This is not part of the ECMA specification, but is available in some implementations (e.g. Firefox).
We can create our own, personalized errors by extending the Error class. In Jurassic Park this could be useful for specific park management problems.
1// Custom error class for dinosaur problems
2class DinosaurEscapeError extends Error {
3 constructor(species, location, message) {
4 super(message);
5 this.name = "DinosaurEscapeError";
6 this.species = species;
7 this.location = location;
8 this.timestamp = new Date();
9 }
10}
11
12function checkEnclosure(enclosureData) {
13 if (!enclosureData.isSecure && enclosureData.containsPredators) {
14 throw new DinosaurEscapeError(
15 enclosureData.species,
16 enclosureData.sector,
17 `DANGER! ${enclosureData.species} escaped from enclosure in sector ${enclosureData.sector}!`
18 );
19 }
20}
21
22try {
23 checkEnclosure({
24 species: "Velociraptor",
25 sector: "B4",
26 isSecure: false,
27 containsPredators: true
28 });
29} catch (error) {
30 if (error instanceof DinosaurEscapeError) {
31 console.error(`${error.name}: ${error.message}`);
32 console.error(`Species: ${error.species}, Location: ${error.location}`);
33 console.error(`Event time: ${error.timestamp}`);
34
35 // Activate safety procedures
36 activateEmergencyProtocols(error.location);
37 evacuateVisitors(error.location);
38 alertSecurityTeam(error);
39 }
40}To effectively handle errors, we must be able to identify them. In the catch block we can check the error type using the instanceof operator or the name property.
1try {
2 // Code that may generate different types of errors
3 const parkSystems = null;
4 console.log(parkSystems.securityStatus); // TypeError
5} catch (error) {
6 if (error instanceof TypeError) {
7 console.error("Type error:", error.message);
8 // Recovery after type error
9 initializeParkSystems();
10 } else if (error instanceof ReferenceError) {
11 console.error("Reference error:", error.message);
12 // Recovery after reference error
13 } else {
14 console.error("Unknown error:", error.message);
15 // General recovery procedure
16 }
17}Every error object in JavaScript has standard properties:
1try {
2 const securityCameras = undefined;
3 securityCameras.forEach(camera => camera.activate());
4} catch (error) {
5 console.error("Error name:", error.name); // "TypeError"
6 console.error("Message:", error.message); // "Cannot read property 'forEach' of undefined"
7 console.error("Call stack:", error.stack); // Full stack trace with line info
8}Handling errors in asynchronous code requires a special approach. With promises we use the
catch() method or the catch block in an async/await construct.1// Error handling with promises
2fetchDinosaurData()
3 .then(data => processDinosaurData(data))
4 .catch(error => {
5 console.error("Error fetching dinosaur data:", error);
6 return getBackupDinosaurData(); // Backup plan
7 });
8
9// Error handling with async/await
10async function monitorDinosaurs() {
11 try {
12 const data = await fetchDinosaurData();
13 processDinosaurData(data);
14 } catch (error) {
15 console.error("Monitoring error:", error);
16
17 // Different recovery procedures depending on error
18 if (error instanceof NetworkError) {
19 await switchToOfflineMode();
20 } else if (error instanceof AuthenticationError) {
21 await refreshSecurityCredentials();
22 return monitorDinosaurs(); // Try again
23 } else {
24 notifyAdministrator(error);
25 }
26 }
27}As Dr. Alan Grant said: "The best defense is knowledge." Understanding the different types of JavaScript errors allows you to better diagnose problems, write more resilient applications, and effectively handle unexpected situations — both in Jurassic Park and in your code.
In the next exercise we'll look more closely at how to throw custom errors using the
throw statement and how to handle errors with the try...catch...finally block — essential tools for every developer, just as a solid cage is essential for every raptor trainer!