Course contentsShow
← JavaScript
Lesson 1234 of 2,72328. CallbacksFree lesson

Checking for Errors Before Data

Always test if the error parameter is truthy before accessing result data.

Checking for Errors Before Data

You'll learn why you must always check the error parameter first in error-first callbacks before touching any data.

The Golden Rule

In error-first callbacks, the first parameter is the error and the second is the result. Here's the critical pattern: always check if the error is truthy before accessing the data parameter.

Why? Because if an error occurred, the data parameter might be undefined, null, or contain incomplete/corrupted information. Accessing it without checking could cause your program to fail silently or behave unpredictably.

The Pattern in Action

function readConfig(callback) {
  // Simulating an error-first callback
  const error = new Error('File not found');
  const data = undefined;
  callback(error, data);
}

// ❌ WRONG: accessing data without checking error
readConfig((err, data) => {
  console.log(data.config); // TypeError if data is undefined!
});

// ✅ CORRECT: check error first
readConfig((err, data) => {
  if (err) {
    console.error('Failed to read config:', err.message);
    return; // Stop execution here
  }
  // Only now is it safe to use data
  console.log(data.config);
});

Think of It Like a Traffic Light

Imagine the error parameter as a red light. You must check if the light is red (error exists) before proceeding through the intersection (using the data). Ignoring this check is like running a red light—you're asking for a crash.

The if (err) check acts as your safety gate. If there's an error, handle it and return early. Only in the safe zone below that check should you trust that data contains valid information.

Key Takeaway: Always test if (err) at the start of your error-first callback and return early—only access data after confirming no error exists.