Skip to content

Errors, Logs and Knowing What Happened

Summary

Teaches error handling, structured logs, request IDs, monitoring, uptime checks and alerts, and how to notice a job that never ran as well as one that failed.

Concepts Covered

This chapter covers the following 24 concepts from the learning graph:

Concept Concept Impact Score
Error 21
Exception 18
Try-Catch Block 7
Bare Catch Block 5
Named Failure 1
User-Facing Error Message 2
Stack Trace Exposure 1
Logging 58
Log Level 1
Structured Logging 3
Secrets in Logs 1
Raw HTTP Logs 1
Request ID 2
Request Path Tracing 1
Error Tracking Service 10
Monitoring 41
Monitoring Dashboard 4
Uptime Check 11
Health Check Endpoint 10
Alert 13
Alert Fatigue 1
Job That Never Ran 11
Heartbeat Check 10
Orphaned Work Sweep 1

Prerequisites

This chapter builds on concepts from:


The Refill That Wasn't There

A woman stops at the pharmacy on her way home from work to pick up her monthly refill. She has done this every month for two years, and the white paper bag is usually waiting in the bin behind the counter. This time the pharmacist types her name, reads the screen and shakes his head. Nothing is ready.

He checks the day's log. Every prescription that came in today is listed there, each with a time, a doctor and a number. Hers isn't one of them. Nothing went wrong inside the pharmacy. Her doctor's office was supposed to send the renewal, and it never arrived. A renewal that never arrives leaves no line in anyone's log, so the screen has nothing to show.

Welcome to Chapter 12

Sawyer waving welcome A quiet app can mean it works, or it can mean it stopped. Right now you may not be able to tell which. By the end of this chapter you'll know where to look when a member says "it didn't work," and you'll hear about a stopped job before a member does.

The pharmacy's computer is good at reporting things that happen. It warns when two drugs clash, when an insurance claim bounces and when a dose looks too high. It warns so often that pharmacists learn to click past most of the warnings without reading them. What it can't do on its own is notice a refill that should have come in and didn't. Many pharmacies now keep track of when each regular refill is due, and ask the doctor's office for the renewal when it's late. That habit is the only thing in the building that would have caught this one.

Your app has the same problem. When it works, it's quiet. When it breaks in some ways, it's also quiet. This chapter is about telling those two silences apart. It covers how code reports a failure and how the app keeps a written record of what it did. Then it shows how to watch the app from outside, and how to notice the hardest failure of all: work that never happened.

Errors and Exceptions

An error is anything that stops code from doing what it was asked to do. A database doesn't answer. A vendor sends back nonsense. A member uploads a file the app can't read. A line of code tries to read a field from something that turned out to be empty. Errors are normal. Every app that talks to a network, a disk or a person meets them every day. What matters is what the code does next.

In the languages your agent writes, most errors arrive as exceptions. An exception is a signal that code raises when it can't continue. It stops the current function and travels back up through every function that called it, looking for code that will deal with it. Programmers say the code "throws" an exception. If nothing deals with it, the exception reaches the top. In an Express server, that means the request fails and the member sees an error. In a background job, the job stops.

Here is how that looks in the dating-safety app. A member starts a scan. Its Express route for scans calls a function that runs the eight checks. One check calls the image-search adapter, and the adapter calls the vendor. That vendor's server is down, so the network call throws an exception.

  1. The adapter's call to the vendor fails and throws.
  2. The adapter has no code to handle it, so the exception leaves the adapter.
  3. It reaches the function that runs the checks. That function has no handling either.
  4. It reaches the route. If the route has none, Express catches it at the top and sends the browser a 500 status code, which Chapter 2 described as "something went wrong on the server." Express 5, the current version, does this on its own, even for routes that wait on a network call. Express 4 needed extra code to catch failures in those routes.

That path is not the worst outcome. This scan failed loudly. The member knows something went wrong, and if the app is watched at all, someone can find out. Worse outcomes come from code that catches the exception and then does the wrong thing with it.

Try-Catch Blocks

A try-catch block is the code that deals with an exception. The try part holds code that might fail. And catch holds what to do if it does. When an exception is thrown inside try, it stops traveling and the code in catch runs.

Below, a try-catch block wraps the image-search call. In plain words, it says: try the search, and if the vendor took too long, mark this check "not checked" and carry on. If anything else went wrong, throw the exception again so it keeps traveling. VendorTimeout is a kind of exception the adapter throws when the vendor doesn't answer in time, and throw err sends any other exception on its way.

try {
  return await imageSearch(photo);
} catch (err) {
  if (err instanceof VendorTimeout) {
    return { check: "image-search", outcome: "not_checked", reason: "timeout" };
  }
  throw err;
}

This is the shape of good error handling. It catches one failure it understands, does something deliberate about it, and lets every other failure keep going. The "not checked" result is the three-state check result from Chapter 9, and it keeps the no-false-all-clear rule from Chapter 1. That rule either holds or breaks inside the catch block.

Bare Catch Blocks

A bare catch block is a catch block that catches every exception and then does nothing useful with it. It might be empty. It might print the error to the console and carry on. It might return an empty list or a default value. In each case the failure goes in and nothing comes out.

try {
  return await imageSearch(photo);
} catch {
  return { matches: [] };
}

This one reads as harmless. It keeps the scan from crashing, which is probably why an agent wrote it. But look at what it does when the vendor is down. The search failed, and the code reports "no matches found." On the results page that becomes "this photo doesn't appear anywhere else on the web," which is a clean result. Chapter 9 calls this a failure read as empty. Usually a bare catch block is how it gets into the code.

Agents write bare catch blocks often, for an understandable reason. When you ask an agent to make an error go away, the fastest way is to catch it and move on. It does go away, from the screen. It doesn't go away from the app. When the dating-safety app was reviewed, it had about 24 bare catch blocks. None of them crashed anything. Each was a place where a failure could disappear without a trace.

A fix that only hid the error

Sawyer pointing out a pitfall When your agent says it fixed an error, look in its change for a new catch. If the error stopped showing because a catch now returns an empty list or a default, nothing was fixed. The failure just went quiet.

Not every bare catch block is dangerous. One around an optional analytics call costs little if it swallows a failure. The ones that matter sit around must-be-right parts: the checks, the score, payments, deleting a member's data, and anything that tells a member something was done.

Named Failures

The fix for a bare catch block is to handle named failures. A named failure is a specific, expected way that an operation can go wrong, given its own name in the code so it can be handled on purpose. VendorTimeout, RateLimited, PhotoTooLarge and PaymentDeclined are named failures. Each one comes with a decision about what to do: mark the check not checked, wait and retry, tell the member the file is too big, ask for another card. Anything that isn't a named failure is unexpected, and unexpected failures should keep traveling until something reports them.

Try sorting some catch blocks yourself. Each one below comes from the kind of code an agent writes for an app like this one.

Diagram: Catch Block Triage

Run the Catch Block Triage MicroSim Fullscreen

Catch Block Triage

Type: microsim sim-id: catch-block-triage
Library: p5.js
Status: Specified
Bloom Level: Evaluate
Bloom Verb: judge
Learning Objective: The learner will judge each of ten catch blocks from an Express app as swallowing the failure, turning it into a false answer, or handling it on purpose.

Prerequisites: error, exception, try-catch block, bare catch block, named failure, "not checked" result, no false all-clear rule (all defined in the sections above or in Chapters 1 and 9).

Evidence of Mastery: The learner assigns each of the ten code cards to one of three verdicts. An assignment is correct when it matches the Correct verdict column in Content. Mastery is 8 of 10 correct on the first attempt. Reading the code and opening the hint are exploration, not evidence.

Misconceptions: (1) A catch block that logs the error has handled it. (2) Code that doesn't crash is safe. (3) Every catch block that catches all errors is bad, even one that tells the member plainly and reports the failure.

Instructional Rationale: Evaluate-level judging asks the learner to apply a standard to cases that look alike. All ten cards have the same try-catch shape, so the learner must read what each catch does with the failure rather than judge by appearance.

Content:

The three verdicts, shown with these definitions:

  • Swallows the failure: the code carries on as if nothing went wrong, and nothing outside the code learns about it.
  • Turns it into a false answer: the code returns a result that looks like success or a clean result.
  • Handles it on purpose: the code deals with a failure it understands, or tells someone plainly, and lets other failures keep traveling.

The ten cards, in TypeScript, shown verbatim:

# Code shown Correct verdict Why (shown as feedback)
1 try { await sendReceiptEmail(member) } catch {} Swallows the failure The receipt doesn't send, and nothing anywhere records that it didn't.
2 try { return await imageSearch(photo) } catch { return { matches: [] } } Turns it into a false answer A failed search becomes "no matches," which reads as a clean photo.
3 try { return await imageSearch(photo) } catch (err) { if (err instanceof VendorTimeout) return { outcome: "not_checked" }; throw err } Handles it on purpose A named failure becomes "not checked," and every other failure keeps traveling.
4 try { await db.insert(scans).values(scan) } catch (err) { console.log(err) } Swallows the failure Printing the error isn't handling it. The route carries on as if the scan was saved.
5 try { score = computeScore(results) } catch { score = 100 } Turns it into a false answer A failure in scoring becomes a perfect score, the worst false all-clear there is.
6 try { await stripe.refunds.create({ payment_intent: id }) } catch (err) { logger.error({ err, paymentId: id }, "refund failed"); throw new RefundFailed(id) } Handles it on purpose It records the failure with the payment ID and raises a named failure the caller must deal with.
7 let body; try { body = JSON.parse(text) } catch { /* ignore */ } Swallows the failure Later code reads an empty body and fails somewhere far from the cause.
8 try { return await phoneLookup(num) } catch (err) { if (err instanceof RateLimited) { await wait(2000); return await phoneLookup(num) } throw err } Handles it on purpose It retries once for one named failure and lets everything else keep traveling.
9 try { await smsVendor.send(code) } catch { return res.json({ sent: true }) } Turns it into a false answer The member is told a code was sent when it wasn't.
10 try { await deletePhotos(memberId) } catch (err) { errorTracker.capture(err); res.status(500).json({ message: "We couldn't delete your photos yet. We've been told and will try again." }) } Handles it on purpose It catches everything, but it reports the failure and tells the member plainly what happened.

Provenance: The pattern of bare catch blocks and failures read as empty comes from the dating-safety app (research/seed-notes.md: about 24 bare catch blocks; a failed search call read as "no results"). The ten code cards are illustrative and must be labeled "illustrative code."

Rules: Each card has exactly one correct verdict. A card is "Turns it into a false answer" when the catch returns or sends a value that reports success or a clean result. A card is "Swallows the failure" when the catch does nothing, or only prints or ignores the error, and the code carries on. A card is "Handles it on purpose" when the catch acts on a named failure and rethrows the rest, or reports the failure and tells the user plainly. If a card fits "false answer" and "swallows," "false answer" wins.

Learner Activity:

  1. The learner sees card 1 and the three verdicts.
  2. The learner picks a verdict. A hint, available on any card, repeats the three definitions.
  3. The learner presses Check. The card shows correct or incorrect and its Why text.
  4. The learner moves to the next card, in the fixed order 1 to 10.
  5. After card 10, a summary shows how many cards fell in each verdict (4 handled on purpose, 3 swallowed, 3 false answers) and which ones the learner missed.

Feedback: Ten cards, fixed order, one attempt each; a checked card can't be re-answered. Correct: "Right. " followed by the Why text. Incorrect: "This one [correct verdict]. " followed by the Why text. If the learner marks card 4 as "Handles it on purpose," add: "Logging a failure isn't the same as handling it." The correct verdict is revealed on Check. A running count "Cards correct: n of 10" is shown, with "Mastery reached" at 8 or more.

Starting State: Card 1 is shown with no verdict chosen. The prompt reads "What does this catch block do with the failure?"

Chapter Anchors: The dating-safety app had about 24 bare catch blocks. The chapter's two worked examples are cards 3 and 2: the named-failure handler for VendorTimeout and the bare catch that returns an empty list of matches.

Tell your agent

"Find every catch block in this codebase. For each one, tell me in a table: the file, what it catches, and what it does with the failure. Mark any that are empty, only print the error, or return an empty or default value. Start with the ones around the checks, the score, payments and data deletion. Don't change anything yet."

What the Member Sees When Something Breaks

When a failure does reach the member, the app has to say something. A user-facing error message is the text a person sees when something goes wrong, written for that person rather than for the programmer. A good one says what happened in plain words, what the person can do now, and whether their work was kept. It never blames the person, and it never shows internal details.

Stack trace exposure is what happens when an app shows those internal details anyway. A stack trace is the list of every function an exception passed through on its way up, with file names and line numbers. It's exactly what a programmer needs to find the bug. On a member's screen it's useless and risky. It tells the member nothing they can act on, and it tells an attacker which framework the app uses, how its folders are laid out, and sometimes which database query failed. When the dating-safety app was reviewed, its error screen showed stack traces. That usually happens in one of two ways. Express's built-in error page includes the trace unless the server runs with NODE_ENV set to production, and error handlers written during development often send the trace on purpose.

This table compares three versions of the same failure: the photo upload fails because storage is down.

Version What the member sees Problem
Stack trace Error: connect ETIMEDOUT at Storage.put (/app/server/storage.ts:41) at uploadRoute (/app/server/routes/scans.ts:88) Shows file paths and internals. Tells the member nothing they can do.
Vague "Oops! Something went wrong." Safe, but the member doesn't know whether to retry, wait, or whether their photos were saved.
Plain "We couldn't save your photos just now. Nothing was uploaded. Please try again in a few minutes." Says what happened, what was kept, and what to do.

The stack trace still matters. It just goes somewhere else: into the logs and the error tracker, which the rest of this chapter covers.

Tell your agent

"Make sure no stack trace, file path or raw error text can ever reach the browser in production. Add one error handler at the end of the Express app that logs the full error on the server and sends the browser a short plain message. Then write a test that forces a route to throw and checks that the response contains no file paths. Show me your plan before you change anything."

Logging: The App's Written Record

Think about how you'd find out what went wrong with a delivery. You'd look at the tracking page: picked up at 9:02, left the warehouse at 11:40, out for delivery at 7:15 the next morning. Each line is short, has a time, and says one thing that happened. When the package doesn't arrive, those lines tell you where it got stuck.

Logging is the practice of having an app write down what it does as it does it, one line per event, so that someone can later find out what happened. Each line is a log entry. A log entry usually holds the time, how serious the event was, a short message and some details. Entries go to a log stream, which your hosting platform collects and lets you search. On Railway, Vercel and similar platforms you'll find it under a tab called Logs.

Logging matters because almost every other tool in this chapter depends on it. When a member says "my scan said not checked," the logs are where you find out why. When an error tracker shows a new failure, the logs show what led up to it. When a job didn't run, the logs show what did arrive instead. An app with no useful logs can only be debugged by guessing, and an agent asked to fix a bug it can't see will also guess.

Logging One Scan

Here is a scan in the dating-safety app, logged poorly and then logged well. An app often has the poor version when nobody asked for logging. A few console.log lines were left in from development.

starting scan
got results
[object Object]
done

Every line here is true, and none of them help. There's no time, no way to tell which scan they belong to, no sign of which checks ran, and one line is an object the logger couldn't print. If ten members scan at once, these lines mix together and can't be pulled apart.

Here is the same scan logged with intent. Each line has a time, a level, which scan it belongs to, and what happened.

09:14:02.101 info  scan started             scanId=s-551 checks=8
09:14:03.912 info  check finished           scanId=s-551 check=message-patterns outcome=pass ms=1722
09:14:12.190 warn  check not checked        scanId=s-551 check=image-search reason=timeout ms=10000
09:14:12.202 info  scan finished            scanId=s-551 ran=7 notChecked=1

Now a question like "why did scan s-551 show a gap?" has an answer in four lines. The image-search vendor didn't answer within ten seconds, the check was marked not checked, and the other seven ran. Notice what isn't in these lines: the member's name, the photo, the text from the conversation. Chapter 8 explains why personal data stays out of logs. An ID is enough to find the scan in the database when you need to.

Log Levels

In those lines, info and warn are log levels. A log level is a label on each log entry that says how serious it is, so you can filter out the routine lines and find the important ones. Most logging tools have at least these four.

Level Use it for Example in the dating-safety app
debug Detail useful only while building The raw vendor response for one check
info Normal events worth a record A scan started; a scan finished
warn Something went wrong, and the app handled it A check timed out and was marked not checked
error Something went wrong, and the app couldn't handle it Saving the scan to the database failed

In production, debug lines are usually turned off, because they're noisy and can hold details you don't want stored. Errors are the lines worth an alert, which comes later in this chapter.

Structured Logging

That good example is readable, but it's still a line of text. Structured logging means writing each log entry as data with named fields, usually as JSON, instead of as a sentence. The log platform can then filter on any field: every entry where check is image-search and outcome is not_checked, say, across the last week. Here is one of the lines above as a structured entry.

{"time":"2026-11-07T09:14:12.190Z","level":"warn","msg":"check not checked",
 "scanId":"s-551","check":"image-search","reason":"timeout","ms":10000}

For an Express app, a logging library such as pino writes entries like this with one line of setup. You don't need to read JSON logs by eye. Your platform's search box does that for you.

Secrets in Logs

Logs are kept for days or weeks, and more people and tools can read them than can read your environment variables. Secrets in logs is the leak that happens when an API key, password, session token or other secret gets written into a log entry. Chapter 6 lists the ways secrets leak; this is the one that comes from logging.

It usually happens by accident. Code logs a whole incoming request to help with debugging, and the request's headers hold the member's session token. Code logs a vendor call in full, and the vendor takes its API key in the URL. Code logs the app's configuration at startup to show which settings loaded, and the configuration holds every key. The fix has two parts. Log chosen fields rather than whole objects. And set the logger's redaction option, which replaces named fields such as authorization, password and apiKey with a placeholder before anything is written.

Raw HTTP Logs

Your own code's logs show what your code did. Your hosting platform keeps a second kind. Raw HTTP logs are the platform's record of every HTTP request that reached your app: the time, the method, the path, the status code and how long the response took. Your code doesn't write them and can't forget to. They exist even for requests your code never handled, which makes them the place to look when your own logs are silent. The story later in this chapter turns on that.

Tell your agent

"Set up structured logging for the server with pino. Every log entry should have a time, a level, a message and named fields. Log the start and end of each scan and the outcome of each check, with the scan ID and check name. Never log member names, photos, message text, request headers or any secret, and set the logger to redact fields named authorization, password, token and apiKey. Remove the leftover console.log lines. Show me your plan, and the fields each log entry will hold, before you change anything."

Following One Request Through the App

Each good log line above carried scanId=s-551. That worked because a scan has an ID. Many requests don't: a page load, a login, a payment webhook. And a busy server handles many requests at once, so their log lines arrive mixed together.

A request ID is a unique label the server gives each incoming request the moment it arrives, then attaches to every log entry written while handling that request. Some teams call it a correlation ID. In Express, the ID is made by middleware, the shared code that runs on every request before the route's own code, as Chapter 3 described. The middleware that runs first creates the ID and hands the logger a copy that stamps the ID on every line. The server can also send the ID back to the browser in a response header, so that an error message can show it: "Something went wrong. Reference: r-7f3a." A member who sends you that reference has handed you the exact lines to read.

Request path tracing is following one request through every part of the app it touched, using its request ID: the route, the functions, the adapters, the outside services and the database. You filter the logs to one request ID, and the lines that remain tell the story of that one request from start to finish. When the request calls an outside service, passing the ID along in a header lets you match your logs to the vendor's if you ever need their help.

When it was reviewed, the dating-safety app had no request IDs. With one scan, that's fine. With fifty members scanning at once on a busy evening, it's the difference between reading four lines and reading four hundred. Try it below.

Diagram: Trace a Scan by Request ID

Run the Trace a Scan by Request ID MicroSim Fullscreen

Trace a Scan by Request ID

Type: microsim sim-id: trace-scan-by-request-id
Library: p5.js
Status: Specified
Bloom Level: Analyze
Bloom Verb: attribute
Learning Objective: The learner will attribute a member's failed check to the one log entry that caused it, by tracing a mixed log stream through a single request ID.

Prerequisites: logging, log level, structured logging, request ID, request path tracing, "not checked" result, timeout (all defined in this chapter or Chapter 9).

Evidence of Mastery: The learner answers three questions in order: which request ID belongs to the member's scan, which log entry explains the gap, and which part of the request path failed. Each answer is correct when it matches the Answer column in Content. Mastery is all three correct with no more than one wrong attempt in total. Filtering and scrolling the log are exploration, not evidence.

Misconceptions: (1) The entry at error level is always the cause. (2) The last entry for a request is where it failed. (3) If the scan finished, nothing went wrong.

Instructional Rationale: Attributing a symptom to its cause is an Analyze task: the learner must separate one request's entries from others that look alike. Interleaved entries and an error-level line from a different request force the learner to use the request ID rather than scan by level or order.

Content:

The member's message, shown first: "My scan around 9:14 this morning (scan s-551) says the photo search was not checked. Why?"

The log stream, twelve entries in this order:

# Time Level Request ID Message
1 09:14:02.101 info r-7f3a POST /api/scans started, scanId=s-551, checks=8
2 09:14:02.140 info r-2c91 GET /api/scans/s-548 results page requested
3 09:14:02.188 info r-7f3a check=image-search adapter call started
4 09:14:02.190 info r-7f3a check=message-patterns adapter call started
5 09:14:02.305 info r-b04e POST /api/scans started, scanId=s-552, checks=8
6 09:14:02.331 info r-2c91 GET /api/scans/s-548 returned 200 in 191 ms
7 09:14:03.912 info r-7f3a check=message-patterns outcome=pass ms=1722
8 09:14:04.020 info r-b04e check=image-search adapter call started
9 09:14:06.447 info r-b04e check=image-search outcome=pass ms=2427
10 09:14:12.190 warn r-7f3a check=image-search vendor did not answer within 10000 ms, outcome=not_checked
11 09:14:12.202 info r-7f3a POST /api/scans finished, scanId=s-551, ran=7, notChecked=1
12 09:14:12.640 error r-b04e check=phone-lookup vendor returned 401, outcome=not_checked

The three questions and answers:

# Question Choices Answer Why (feedback)
1 Which request ID belongs to scan s-551? r-7f3a, r-2c91, r-b04e r-7f3a Entry 1 links scan s-551 to request r-7f3a.
2 Which entry explains why the photo search was not checked? Any of entries 1 to 12 Entry 10 Entry 10 is the image-search check for r-7f3a, and it timed out. Entry 12 is an error, but it belongs to a different member's scan.
3 Which part of the request path failed? Browser, Express route, image-search adapter, image-search vendor, database Image-search vendor The adapter started the call (entry 3), but the vendor didn't answer within 10 seconds. The route and the rest of the scan finished normally (entry 11).

Provenance: Illustrative log data, and the sim must label it "illustrative." Scan s-551, the 10-second timeout and entries 1, 7, 10 and 11 match the worked example in the section "A Worked Example: Logging One Scan." The 10-second timeout matches Chapter 1's worked trade-off.

Rules: The learner can show all entries or only those whose request ID matches one chosen ID. Question 2 accepts only entry 10. Question 3 accepts only "Image-search vendor." Questions unlock in order: question 2 appears after question 1 is answered correctly or revealed.

Learner Activity:

  1. The learner reads the member's message and the full log stream of twelve entries.
  2. The learner answers question 1. Once it's correct or revealed, the filter by request ID becomes available.
  3. The learner filters to one request ID. Only that request's entries remain. The learner should notice that r-7f3a has six entries and tells a complete story.
  4. The learner answers question 2 by choosing an entry, then question 3 by choosing a part of the path.
  5. After question 3, the sim shows the path for r-7f3a as a short sequence: route, adapter, vendor (timed out), route finished, with each step linked to its entry number.

Feedback: Three questions, fixed order, two attempts each. Correct: "Right. " followed by the Why text. Incorrect on question 2 with entry 12: "That's an error, but look at its request ID. It belongs to scan s-552." Any other incorrect answer: "Not quite. " followed by a hint to filter by the request ID from question 1. After the second wrong attempt, the answer and its Why text are shown. A count "Questions correct: n of 3" is shown.

Starting State: All twelve entries are shown unfiltered, with the member's message above them. The prompt reads "Which of these lines belong to this member's scan?"

Chapter Anchors: Scan s-551, request reference r-7f3a, a 10-second timeout, seven checks ran and one was not checked, eight checks per scan.

Tell your agent

"Add a request ID to every request the Express server handles. Create it in the first middleware and attach it to every log entry written during that request. Send it back in an X-Request-Id response header, and include it as a reference in every error message a member sees. Pass it to outside vendors in a header where they accept one."

Error Tracking Services

Logs record everything, which is their strength and their weakness. A failure that happens a hundred times a day can still be hard to see in a stream of a million routine lines. And nobody reads logs unless they already know something is wrong.

An error tracking service is an outside tool that collects every unhandled exception from your app, groups repeats of the same failure together, and tells you when a new one appears. Sentry is the best known; Rollbar, Bugsnag and Honeybadger do the same job. You add a small library to the server and the front end and give it a project key. From then on, each exception is sent with its stack trace, the request that caused it, the request ID and which deploy was running. That's where the stack trace from the error screen belongs: in a private tool that only you and the people you invite can open.

Grouping makes it useful. Suppose a change last Tuesday broke the results page for members whose scan has no photos. In the logs that's 312 error lines scattered across six days. In an error tracker it's one entry: "TypeError: Cannot read properties of undefined (reading 'url')." It was first seen Tuesday at 4:10 p.m., right after a deploy. It happened 312 times to 41 members, and one full example is attached. You can hand that one entry to your agent, and the agent has the stack trace, the input and the time it started.

An error tracker sees only exceptions that reach it. A bare catch block hides a failure from the error tracker as well as from the member. That's one more reason to fix those blocks first. Once named failures are handled and everything else keeps traveling, the error tracker sees what it should.

When it was reviewed, the dating-safety app had no error tracking. Most error trackers have a free tier large enough for an app of its size, and setup takes under an hour.

Tell your agent

"Add Sentry to the Express server and the React front end. Read the project key from an environment variable. Attach the request ID and the deploy version to every event, and make sure no member names, photos, message text or secrets are sent. Show me the settings that control what gets sent before you deploy. Then throw a test error from a hidden route and confirm it shows up in Sentry with its stack trace."

Monitoring: Watching the App From Outside

Everything so far happens inside the app. Code reports its own failures. That fails in one important case: when the app isn't running. A server that has crashed writes no logs and reports no exceptions. To notice that, something outside the app has to keep checking on it.

Monitoring is the practice of watching a running app all the time, from inside and outside, and comparing what you see against what normal looks like. Its purpose is to find problems before your users tell you. It covers whether the app is up, how fast it answers, how many requests fail, how much work it's doing, and whether the jobs that should run did run. Logging and error tracking are the app's own record. Monitoring adds checks the app can't skip.

Monitoring uses a few kinds of signal. Some are counts, such as requests per minute and errors per minute. Some are times, such as how long a scan takes. Some are yes-or-no, such as "did the server answer?" Each is useful only when you know its normal value. Five errors an hour might be normal for one app and an emergency for another.

What to Watch for the Dating-Safety App

Here is a good-enough monitoring plan for the dating-safety app, built from the must-be-right parts in Chapter 1. Each row names one signal, what normal looks like, and what would be worth acting on. These normal values are illustrative; your app's own numbers come from watching it for a week or two.

Signal Why it matters Normal (illustrative) Worth acting on
Server answers its health check If not, no member can scan Every check succeeds Two failed checks in a row
Share of requests returning a 500 status Unhandled failures reaching members Under 1% Over 5% for 10 minutes
Time for a full scan Members leave if scans are slow 8 to 15 seconds Most scans over 30 seconds
Share of checks marked not checked, per vendor A vendor is down or out of credit Under 5% Over 25% for one vendor
Nightly purge job finished Retention rules depend on it Once a day No run in 26 hours
New exception type in the error tracker Something new broke None most days Any new type after a deploy

That fourth row deserves a closer look. The no-false-all-clear rule keeps a down vendor from looking like a clean result to the member. But a check that is never anything but "not checked" is still broken, and only monitoring tells the builder. The member sees a truthful gap. The builder needs to see a pattern of gaps. Vendor-credit alerts, which the app already has, are one piece of this, and Chapter 13 covers alerts on spending.

Monitoring Dashboards

A monitoring dashboard is a single page that shows an app's most important signals as charts and numbers, all at once, so a person can see whether things look normal at a glance. Your hosting platform gives you a basic one for free: requests, response times, memory and CPU. Error trackers and uptime services have their own.

A dashboard is good for two moments. The first is right after a deploy, when you want to see that the error line stayed flat. The second is during a problem, when you want to see when it started and what else changed at the same time. A dashboard is poor at catching problems on its own, because it only helps when someone is looking. Nobody watches a dashboard at 3 a.m. That job belongs to alerts.

For an app this size, one dashboard with the six signals from the table is enough. More charts don't make the app safer; they make the important chart harder to find.

Uptime Checks and Health Check Endpoints

An uptime check is a request that an outside service sends to your app on a fixed schedule, often every one to five minutes, to confirm that it answers. If the app doesn't answer, or answers with an error, the service tells you. UptimeRobot, Better Stack and Pingdom are common choices, and most have a free tier. Because the check comes from outside, it catches failures nothing inside the app can report: a crashed server, a failed deploy, an expired domain, a platform outage.

An uptime check needs something to call. A health check endpoint is a route in your app, usually /health, whose only job is to report whether the app is working. At its simplest, it just answers "ok," which proves the server is running. A more useful version also checks the things the app can't work without, such as the database.

Here is a health check endpoint for the Express server. It runs the smallest possible database query, select 1, which asks the database to return the number 1. If that works, the endpoint answers with status 200 and "ok." If it fails, the endpoint answers with status 503, which means "service unavailable," and the uptime check treats that as down.

app.get("/health", async (req, res) => {
  try {
    await db.execute(sql`select 1`);
    res.status(200).json({ status: "ok" });
  } catch (err) {
    logger.error({ err }, "health check failed: database");
    res.status(503).json({ status: "unavailable" });
  }
});

This catch block is not a bare one. It handles the failure on purpose: it logs it and returns a status that says the app is down, which is the truth.

Keep vendors out of /health

Sawyer pointing out a pitfall Don't make the health check call your paid vendors. An uptime check every minute is 1,440 calls a day, so the check would cost money and fail whenever any one vendor had a bad minute. Vendor health belongs in the "not checked" signal from the monitoring table, not in /health.

When it was reviewed, the dating-safety app had no uptime check. A crash at night would have stayed invisible until a member wrote in the next morning.

Tell your agent

"Add a GET /health route to the Express server that runs select 1 against the database and returns 200 with status ok, or 503 if the query fails. Don't call any outside vendor from it. Then list the steps for me to set up a free uptime check that calls /health every five minutes and emails me after two failures in a row."

Alerts and Alert Fatigue

An alert is a message that a monitoring tool sends to a person when a signal crosses a line you set, so the person learns about a problem without watching for it. It might be an email, a text, a phone notification or a message in a chat channel. In the pharmacy, it's the warning that pops up on the pharmacist's screen. It turns "something is wrong" into "someone knows something is wrong."

Each alert needs four things decided ahead of time: the signal, the line, how long it has to stay over the line, and who gets told. "Two failed uptime checks in a row, text the builder" is a complete alert. "Errors are high" is not, because nobody knows what high means or who should act.

Make each alert fire once on purpose

Sawyer sharing a tip An alert that has never fired might not work. When you set one up, set it off once: point the uptime check at a wrong URL, or skip a job's ping. Then check that the message reached your phone or inbox.

Here are three alert rules for the dating-safety app, with the reasoning behind each.

Alert Fires when Goes to Why this line
App down Two uptime checks in a row fail Text message One failure can be a blip. Two in a row, five minutes apart, means members can't scan.
Vendor failing One vendor's checks are over 25% not checked for 30 minutes Email Members still get a truthful result, so this can wait an hour, but not a week.
Job missed The nightly purge hasn't reported in 26 hours Email Gives the job a two-hour grace period past its 24-hour schedule before anyone is bothered.

Alert fatigue is what happens when alerts fire so often, or so often for nothing, that people start ignoring them. It's the pharmacist clicking past the twentieth drug warning of the day. A builder who gets forty emails a day from the error tracker, most about one harmless warning, will set up a filter that sends them all to a folder. The day a serious one arrives, it goes into the same folder.

Alert fatigue has plain fixes. Alert only on things a person must act on. Make every alert say what to do next. When an alert fires and no action was needed, change its line or delete it the same day. A good-enough app has very few alerts, and each one means something.

Tell your agent

"List every alert this app sends today: from the error tracker, the hosting platform, vendors and our own code. For each one, tell me what triggers it, who gets it, and how often it fired in the last month. Flag any that fired more than ten times, and any where the right response is to do nothing."

The Job That Never Ran

Everything in this chapter so far catches failures that make some noise: an exception, an error line, a check that doesn't answer. One kind of failure makes none at all.

This book's author runs an online sticker business. Some of its work runs on a schedule, as scheduled jobs (Chapter 3 introduced them). One day those jobs had stopped. Nothing had crashed. No error had been logged, and the app's own logs had nothing about the jobs at all, which at first looked like good news.

It came down to one word. Chapter 2 described HTTP methods, the GET and POST that say what kind of request is being made. The scheduler was calling each job's route with a GET. The framework only ran that route's code for a POST. So every scheduled call arrived, and the job's code never ran. Because the code never ran, its error handling never ran, and neither did its logging. There was nothing for any tool to report.

Only one place showed the failure: the platform's raw HTTP logs. There, each scheduled call was listed, at the right time, with its method. The line looked something like this illustrative one:

03:00:00.012  GET  /api/jobs/nightly  (from scheduler)

Once he saw "GET," the fix was a one-line change. Finding it took hours, because every tool he looked at first was built to report on code that ran.

A job that never ran is scheduled or background work that was supposed to happen and didn't, without any error, because the code that would have reported a problem was never reached. A config change deleted the schedule. A scheduler called the wrong method or the wrong URL. A deploy turned the scheduler off. A queue filled up and the job waited forever. In each case, the logs, the error tracker and the job's own try-catch blocks are all silent, because they live inside the job.

Who would notice?

Sawyer thinking it over For each scheduled job, ask: if this stopped tomorrow, who would notice, and when? If the answer is "a member, weeks from now," that job needs something outside it that expects to hear from it.

The dating-safety app will have a job like this once it fixes its retention gap. Chapter 8's fix is a purge job that deletes data about people who never signed up, after a set time. If that job stops running, nothing breaks that anyone can see. Everything keeps working. The data just quietly stays, past the date the app promised to delete it.

Heartbeat Checks

To catch a job that never ran, turn its silence into a signal. A heartbeat check is a monitor that expects to hear from a job on a schedule and alerts you when it doesn't. The job sends a small request, called a ping, to the monitoring service each time it finishes. The service knows the job should ping once a day, say, with a grace period. If no ping arrives in time, it sends an alert. Healthchecks.io, Cronitor and Better Stack offer heartbeat checks, often on a free tier.

A heartbeat check reverses the usual logic. An uptime check asks "did the app answer?" An error tracker asks "did anything fail?" A heartbeat check asks "did the thing I expected happen?" It's the only one of the three that notices an absence, the way a pharmacy notices a refill that's late. In the sticker business story, a heartbeat on each job would have sent an alert the first morning, before anyone noticed missing work.

Put the ping at the end of the job, after the work succeeded. A ping at the start proves only that the job began. Here is the purge job with a heartbeat. In plain words: delete the expired rows, log how many, then ping the heartbeat URL. HEARTBEAT_PURGE_URL is an environment variable holding the address the monitoring service gave you for this job.

export async function nightlyPurge() {
  const deleted = await purgeExpiredRecords();
  logger.info({ job: "nightly-purge", deleted }, "purge finished");
  await fetch(process.env.HEARTBEAT_PURGE_URL!);
}

If the purge throws, the ping never goes, and the heartbeat alerts. If the scheduler never calls the job, the ping never goes, and the heartbeat alerts. One line covers both.

Orphaned Work Sweeps

There's a cousin of the job that never ran: the job that started and never finished. A scan begins, its row in the database says "running," and then the server restarts in the middle of it. Chapter 14 explains how a deploy can do this to scans in flight. The process that was running the scan is gone, so nothing will ever mark it done or failed. A member sees a spinner forever.

An orphaned work sweep is a scheduled job that looks for work stuck in an unfinished state for longer than it could possibly take. It then finishes, fails or retries that work on purpose. The dating-safety app already had one for orphaned scans, and it's one of the things the agent got right. A scan normally takes under a minute, so a sweep can treat any scan still "running" after fifteen minutes as orphaned. (The fifteen-minute line is illustrative.) The sweep marks it failed, records why, and lets the member run it again. Since the sweep is a scheduled job itself, it gets a heartbeat too.

This last diagram asks which of the tools in this chapter would notice each failure first.

Diagram: Which Watcher Notices First

Run the Which Watcher Notices First MicroSim Fullscreen

Which Watcher Notices First

Type: microsim sim-id: which-watcher-notices-first
Library: p5.js
Status: Specified
Bloom Level: Analyze
Bloom Verb: distinguish
Learning Objective: The learner will distinguish, for each of ten failures in the dating-safety app, which watching tool would notice it first, including failures that no watching tool can see.

Prerequisites: bare catch block, error tracking service, uptime check, health check endpoint, heartbeat check, orphaned work sweep, job that never ran, raw HTTP logs, failure read as empty (all defined in this chapter or Chapter 9).

Evidence of Mastery: The learner assigns each of ten failure cards to one of five answers. An assignment is correct when it matches the Answer column in Content. Mastery is 8 of 10 correct on the first attempt. Opening a tool's description is exploration, not evidence.

Misconceptions: (1) An error tracker sees every failure. (2) A quiet app is a working app. (3) If the app is up, its scheduled jobs are running. (4) Watching tools can catch a failure that the code swallowed.

Instructional Rationale: Distinguishing which tool covers which failure requires the learner to break each failure into where it happens and whether any code runs that could report it. Several cards look alike on the surface (two jobs that fail, two outages), so the learner must examine the mechanism, not the symptom.

Content:

The five answers, each with a one-line description the learner can open:

  • Error tracking service: reports exceptions that reach it from code that ran.
  • Uptime check: calls the health check endpoint from outside every few minutes and alerts if it doesn't get "ok."
  • Heartbeat check: expects a ping when a job finishes and alerts if none arrives in time.
  • Orphaned work sweep: finds work stuck as unfinished too long and fails or retries it.
  • None of these: no tool sees it; the fix belongs in the code.

The ten failure cards:

# Failure Answer Why (feedback)
1 A deploy leaves the server unable to start. Uptime check A server that isn't running can't send anything to an error tracker. Only a check from outside notices.
2 A route throws a TypeError for members whose scan has no photos. Error tracking service The code ran and threw, so the exception reaches the error tracker at once.
3 A config change deletes the nightly purge job's schedule. Heartbeat check The job never runs, so it never errors. Only the missing ping shows it.
4 The scheduler calls a job's route with GET, and the framework runs it only for POST. Heartbeat check The job's code never runs. Raw HTTP logs show the GET, but only a heartbeat sends an alert.
5 The server restarts during a deploy, and a scan stays "running" for an hour. Orphaned work sweep Nothing is left to finish the scan. The sweep finds it stuck and marks it failed.
6 At 3 a.m., with no members online, the database stops accepting connections. Uptime check No requests means no exceptions. The health check's database query fails, and the uptime check sees a 503.
7 Receipt emails stop sending, inside a catch block that is empty. None of these The catch swallowed the failure, so no tool ever hears about it. Fix the catch block.
8 The image-search adapter returns "no matches" whenever the vendor errors. None of these The failure is turned into a clean result in the code. Every tool sees success. Fix the adapter.
9 The weekly report job starts, then throws an exception halfway through. Error tracking service The exception reaches the error tracker as it happens. A heartbeat would notice too, but only after its grace period.
10 The app's domain name expires, and the site stops loading. Uptime check The server is fine, but nobody can reach it. Only a check that comes from outside sees that.

Provenance: Cards 4 and 5 come from the chapter's sections "The Job That Never Ran" and "Orphaned Work Sweeps" (the author's story, recorded in research/seed-notes.md, and the dating-safety app's sweep for orphaned scans). Cards 7 and 8 come from the dating-safety app's gaps in research/seed-notes.md (bare catch blocks; a failed search read as "no results"). Cards 1, 2, 3, 6, 9 and 10 are illustrative and must be labeled "illustrative."

Rules: Each card has exactly one answer. "Notices first" means raises the alarm soonest. An error tracker reports an exception within seconds; a heartbeat alerts only after its grace period; an uptime check alerts within its schedule of a few minutes. If code turns a failure into a success or swallows it, the answer is "None of these," because no watching tool can see it.

Learner Activity:

  1. The learner sees card 1 and the five answers. Each answer's description can be opened at any time.
  2. The learner picks an answer and presses Check. The card shows correct or incorrect and its Why text.
  3. The learner moves through the cards in the fixed order 1 to 10.
  4. After card 10, a summary groups the cards by correct answer. The learner should notice that two cards land in "None of these" and that both are code problems, which no watching tool can fix.

Feedback: Ten cards, fixed order, one attempt each; a checked card can't be re-answered. Correct: "Right. " followed by the Why text. Incorrect: "The first to notice is [answer]. " followed by the Why text. If the learner answers "Error tracking service" on card 3, 4 or 7, add: "An error tracker can only report code that ran and threw." The correct answer is revealed on Check. A running count "Cards correct: n of 10" is shown, with "Mastery reached" at 8 or more.

Starting State: Card 1 is shown with no answer chosen. The prompt reads "Which tool would tell you about this first?"

Chapter Anchors: The scheduler sent a GET where the framework expected a POST, and the cause was visible only in raw HTTP logs. A scan normally takes under a minute; the sweep treats a scan still running after fifteen minutes as orphaned. Uptime checks run every one to five minutes.

Tell your agent

"List every scheduled and background job in this app, with how often each should run, and show me the list before changing anything. Then, for each one, add a heartbeat ping to the end of the job, after the work succeeds, reading the ping URL from an environment variable. Then check that every job's route accepts the HTTP method its scheduler actually sends, and show me the scheduler's config next to each route so I can see they match."

Back to the Pharmacy Counter

The woman at the counter didn't need a better log. The log was complete, and it listed everything that arrived. She needed someone who knew her refill was due and noticed when the renewal didn't come. And the pharmacist needed fewer warnings, so the ones on his screen got read.

Your app needs the same two things. Logs, error tracking and uptime checks report what happened. A heartbeat on every scheduled job notices what didn't. A few alerts, each one worth reading, tell you when to act. Chapter 13 applies the same watching to money, where a runaway bill stays quiet until it's large.

You can tell the two silences apart

Sawyer celebrating You now know how to tell an app that's quiet because it works from one that's quiet because it stopped. Pick the one job you'd least like to lose and give it a heartbeat this week. Good enough for now, and you know why.

Key Takeaways

  • Most errors arrive as exceptions. A bare catch block makes them vanish; handle named failures on purpose and let the rest keep traveling. The dating-safety app had about 24 bare catch blocks.
  • Show members a plain user-facing error message. Send the stack trace to the logs and the error tracker, never to the screen.
  • Structured logging with a log level and a request ID on every entry lets you follow one request through a busy app. Redact secrets. Raw HTTP logs record requests your code never handled.
  • An error tracking service only sees exceptions that reach it. Monitoring compares the app against normal, and an uptime check on a health check endpoint catches a server that isn't running.
  • Keep alerts few, so each one gets read. Alert fatigue buries the one that matters.
  • A job that never ran makes no error. A heartbeat check turns its silence into an alert, and an orphaned work sweep cleans up work that started and never finished.

See Annotated References