Throw Errors That Explain Themselves

In the last exercise, your loader flagged minutes that came out NaN. That check lives in one place, though. In the season log, seasonMinutes() reported Ruth’s "forty", while formatRun() printed it as 5 km in forty min without a word. Every function that reads a run would need its own check.

Ruth wants one place in the import process that looks at each run record and refuses the ones the program can’t use. In this lesson, you’ll write a function that checks its input and throws an error whose message says which record is wrong, what was expected, and what came in. Start with the field missing from Ruth’s newest file.

Stop a Bad Run With throw

A bad record is cheapest to deal with at the moment it enters the program, before any other function has trusted it. Ruth’s season-log project is as you left it in the last lesson. If you don’t have the files anymore, re-create them in a season-log folder:

This package.json tells Node.js to treat the .js files as ES modules:

Language: JSON Filename: package.json
{ "type": "module" }

The loader in load.js parses a file’s text and reports a broken file by name:

Language: JavaScript Filename: load.js
import { readFileSync } from "node:fs";

export function loadRuns(path) {
  const text = readFileSync(path, "utf-8");
  let runs = [];
  try {
    runs = JSON.parse(text);
  } catch (error) {
    if (error instanceof SyntaxError) {
      console.log(`Couldn't read ${path}.`);
      console.log(`${error.name}: ${error.message}`);
    } else {
      throw error;
    }
  }
  return runs;
}

The report in report.js formats and prints each run:

Language: JavaScript Filename: report.js
export function formatRun(run) {
  const who = `${run.runner} (${run.date})`;
  return `${who}: ${run.distance} km in ${run.minutes} min`;
}

export function printSeason(runs) {
  for (let i = 0; i < runs.length; i++) {
    console.log(formatRun(runs[i]));
  }
}

The function in totals.js adds up the minutes and reports any that become NaN after conversion:

Language: JavaScript Filename: totals.js
export function seasonMinutes(runs) {
  let total = 0;
  for (const run of runs) {
    const minutes = Number(run.minutes);
    if (Number.isNaN(minutes)) {
      console.log(`Run ${run.id}: bad minutes ${run.minutes}`);
    } else {
      total += minutes;
    }
  }
  return total;
}

The program in main.js wires them together:

Language: JavaScript Filename: main.js
import { loadRuns } from "./load.js";
import { printSeason } from "./report.js";
import { seasonMinutes } from "./totals.js";

const runs = loadRuns("new-runs.json");
printSeason(runs);
console.log(`Minutes run: ${seasonMinutes(runs)}`);

Ruth has replaced last week’s runs in new-runs.json with the three from May 9. Priya’s message gave her time but not her distance, so run 12 has no "distance" at all:

Language: JSON Filename: new-runs.json
[
  { "id": 12, "runner": "Priya Nair", "date": "2026-05-09",
    "minutes": 33 },
  { "id": 13, "runner": "Kwame Mensah", "date": "2026-05-09",
    "distance": 80, "minutes": 39 },
  { "id": 14, "runner": "Grace Kim", "date": "5/9/2026",
    "distance": 5, "minutes": 25 }
]

Ruth starts a new module, check.js, with a function that checks one run. If the distance isn’t a number, it throws an error:

Language: JavaScript Filename: check.js
export function checkRun(run) {
  if (typeof run.distance !== "number") {
    const got = JSON.stringify(run.distance);
    throw new Error(
      `Run ${run.id}: distance must be a number, got ${got}`
    );
  }
}

Until now, every error in the season log came from JavaScript itself, and you used throw only to rethrow one in loadRuns(). Here, throw sends a brand-new error that your own code creates.

In checkRun(), which has no catch of its own, throw ends the function on that line, like return. Instead of handing back a result, though, it sends the error to the nearest enclosing catch, running any finally blocks on the way.

A catch that doesn’t want the error can rethrow it, as loadRuns() does. That nearest-catch rule is how the SyntaxError from JSON.parse() reached catch in the video.

The value after throw is a new error object. The new keyword creates a fresh object from Error, and the string you pass becomes its .message.

It’s the kind of object your catch blocks read .message from, and in Node.js, as in every major engine, it records a stack trace when it’s created.

The if at the top of checkRun() is a guard clause: a check at the start of a function that stops it when the input can’t be used, so the code after it can trust what’s left.

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.