Skip to content

16 min read

Error handling and logging in Node.js

In one sentence: An error nobody catches ends the program. A server catches them all: it answers the client with a 500 with no details and an id, and writes the stack trace in its log with that same id. The log is JSON, one line per event, so a person can read it and so can a program.

What you will learn

  • Throw and catch errors with throw and try/catch, async code included.
  • Answer with a 500 that doesn't show the stack trace, with an id to find the error in the log.
  • Write JSON logs with pino, choose their level and search them with grep and jq.
  • Read the configuration from environment variables and refuse to start if something is missing.

Before you start, read: 07-validation.md phase-1/07-environment-variables.md

Imagine the shop’s API is already live. One Saturday, a customer writes to Luis: “when I paid I got a screen full of weird lines, something like at file:///Users/ana/backend-course/….” That customer has seen the server’s insides: its folders, its libraries and the line that failed. They’re no use to the customer; to someone looking for a way to attack the shop, they are.

And Ana doesn’t know what happened: her terminal has hundreds of lines of free text, and none of them says which one was that customer’s.

The server has to fail well: for the customer, a short message and a reference number; for Ana, every detail in the LogA text file where a program writes down what happens, one line for each thing. A web server’s has a line for each request it receives, and it’s the first thing you look at when something fails.Go to definition, with that same number.

The analogy

Think of a restaurant. A cook burns a sauce. The waiter doesn’t bring the pan to the table: he says “there’s been a problem with your dish; your order is number 41.” In the kitchen, the head chef writes in his notebook: “order 41, 9:14 p.m., sauce burned on burner 3.”

If the customer complains, they give the order number, and with it the note is found. And a problem a cook can’t solve ends up with the head chef, who doesn’t let a sauce close the restaurant.

Where the analogy breaks down

  • In a restaurant without a head chef, a burned sauce only spoils one table. In Node, an error nobody catches shuts down the whole program, and leaves every client without service at once.
  • The notebook is read by a person. A log is also read by programs, and that’s why every line follows a fixed format.

The examples that aren’t part of the project go in ~/backend-course/phase-3, outside shop-api. The outputs are from Node 26; the paths, from a Mac (on Linux and WSL they start with /home/ana).

This program reads an order that arrived cut off. JSON.parse turns JSONJSON stands for JavaScript Object Notation.A format for writing data as text, with braces, quotes and colons: {"product":"mug","quantity":2}. People can read it, and so can almost any programming language, and it’s the most common format for the data that travels between a frontend and a backend.Go to definition text into data (you saw it in “JavaScript”):

crash.ts
const order = JSON.parse('{"productId": 1, "quantity": ');
console.log('Order read:', order);

Run it and look at its exit code

Ventana de terminal
node crash.ts
echo $?

What you will see:

<anonymous_script>:1
{"productId": 1, "quantity":
SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at Object.<anonymous> (file:///Users/ana/backend-course/phase-3/crash.ts:1:20)
at Module._compile (node:internal/modules/cjs/loader:1968:14)
at Object..js (node:internal/modules/cjs/loader:2108:10)
at Module.load (node:internal/modules/cjs/loader:1690:32)
at Module._load (node:internal/modules/cjs/loader:1480:12)
at wrapModuleLoad (node:internal/modules/cjs/loader:261:19)
at Module.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:171:5)
at node:internal/main/run_main_module:33:47
Node.js v26.11.1
1

JSON.parse can’t go on with incomplete text, so it throws an ExceptionAn error a program throws when it can’t go on with what it was doing, like reading a JSON that arrives cut off. It travels up through the code until some part catches it; if none does, the program ends.Go to definition: an error that travels up through the code looking for someone to catch it. Here nobody catches it, and Node prints the error and ends.

  • Order read never shows up: the program stopped at line 1.
  • The Stack traceThe list of functions a program was going through when an error was thrown, from the most recent to the oldest, with the file, line and column of each one. It says where it failed, and that’s why it goes to the log and never to whoever made the request.Go to definition is the lines that start with at. The first one from your code says where the error happened: crash.ts:1:20, line 1, column 20. The node:internal ones belong to Node itself.
  • The 1 at the end is the Exit codeThe number a program leaves when it finishes. 0 means it went well, and any other, from 1 to 255, that something failed. The shell keeps it in $?, and scripts check it to decide whether to go on.Go to definition from lesson 3 of Phase 1: something failed.

throw throws an error, try and catch catch it

Section titled “throw throws an error, try and catch catch it”

An error can also be thrown on purpose, as in this new shop Route (on a server)Each combination of HTTP method and URL path that a server knows how to handle, such as GET /products, together with the function that responds to those requests. A request that matches no route gets a 404.Go to definition:

src/app.ts
// A route that fails on purpose, to see what happens with an error nobody expected.
app.get('/error', () => {
throw new Error('Something failed on purpose');
});
  • new Error('…') creates an error with its message. Node adds the stack trace to it at the moment it’s created.
  • throw throws it: the function stops there, and the error goes up to whoever called it, and so on upward, until someone catches it.

To catch it, the code that might fail goes inside a try, and what to do if it fails goes in a catch:

catch.ts
try {
const order = JSON.parse('{"productId": 1, "quantity": ');
console.log('Order read:', order);
} catch (error) {
if (error instanceof Error) console.log('Could not read it:', error.message);
}
console.log('The program goes on');

node catch.ts prints Could not read it: Unexpected end of JSON input and then The program goes on: the error happened in the try, the program jumped to the catch and kept going.

error is whatever was thrown, and throw can throw anything. That’s why its TypeThe kind of data that can go in a place, such as a number, a piece of text or a product with its name and its price. In TypeScript it’s written after a colon (price: number), and it helps find errors before running the program.Go to definition is unknown (“TypeScript”), and error instanceof Error checks that it’s an Error before reading its message.

With async, the error arrives at the await

Section titled “With async, the error arrives at the await”

An async function returns a PromiseA value that isn’t there yet but will arrive, like the text of a file that is being read. Until it arrives, the program can go on with other things; with await, it waits for it.Go to definition, a value that will arrive later. If the function fails, it doesn’t throw the error right away: the promise arrives with the error instead of the value. await waits for that promise and, if it brings an error, throws it on that line, where the catch sees it:

async.ts
async function loadOrder(id: number) {
throw new Error(`Order ${id} does not exist`);
}
try {
await loadOrder(7);
} catch (error) {
if (error instanceof Error) console.log('Could not find it:', error.message);
}
console.log('The program goes on');

node async.ts prints Could not find it: Order 7 does not exist and The program goes on. Now delete the await on line 6 and run it again:

Without the await

Ventana de terminal
node async.ts

What you will see:

The program goes on
file:///Users/ana/backend-course/phase-3/async.ts:2
throw new Error(`Order ${id} does not exist`);
^
Error: Order 7 does not exist
at loadOrder (file:///Users/ana/backend-course/phase-3/async.ts:2:9)
at Object.<anonymous> (file:///Users/ana/backend-course/phase-3/async.ts:6:3)
at Module._compile (node:internal/modules/cjs/loader:1968:14)
at Object..js (node:internal/modules/cjs/loader:2108:10)
at Module.load (node:internal/modules/cjs/loader:1690:32)
at Module._load (node:internal/modules/cjs/loader:1480:12)
at wrapModuleLoad (node:internal/modules/cjs/loader:261:19)
at Module.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:171:5)
at node:internal/main/run_main_module:33:47
Node.js v26.11.1

The program goes on shows up before the error: without await, the try didn’t wait for the promise, and when the error arrived there was no catch left. Node ends with code 1.

Why a server doesn’t go down with every error

Section titled “Why a server doesn’t go down with every error”

In lesson 4, without a FrameworkReady-made code that solves what almost every program of one kind repeats, such as a server (reading each request, deciding which route handles it and responding), and that calls your functions when the time comes. You write only what’s specific to your application. Hono, Express and Fastify are frameworks for servers.Go to definition, the .catch in createServer answered 500 if something failed. Without it, a throw in a route brings down the whole process, and the next request, whoever it comes from, gets Couldn't connect to server.

Hono, like Express or Fastify, wraps each request in its own try/catch. If a route throws an error, Hono catches it, answers 500 with the text Internal Server Error, writes the stack trace in the terminal and keeps serving everyone else.

A program dying isn’t always bad: if it fails at startup (the port is taken, the configuration is incomplete), it’s better for it to end and say why. In production it starts again on its own: Restart=always in systemd does that (lesson 6 of Phase 1), and Docker will do it in Phase 7.

That 500 isn’t JSON, like the rest of the API, and the stack trace Hono writes in the terminal doesn’t say which request it belongs to. This changes that:

src/app.ts
// What doesn't exist: a 404 in JSON, like the rest of the API.
app.notFound((c) => c.json({ error: 'No such route' }, 404));
// Any error that escapes from a route ends up here.
app.onError((error, c) => {
// The errors Hono throws already carry their status code (malformed JSON is a 400): they're
// answered in JSON, like the rest of the API.
if (error instanceof HTTPException) {
return c.json({ error: 'The request cannot be read', detail: error.message }, error.status);
}
const id = c.get('requestId');
// The error and its stack trace go to the log; the client gets a message and the id to find it.
log.error({ err: error, requestId: id }, 'uncaught error');
return c.json({ error: 'Internal server error', requestId: id }, 500);
});
  • app.notFound answers when no route matches: a 404 in JSON.
  • app.onError receives any error that escapes from a route or a MiddlewareA function a server runs with the requests of the routes it’s registered on (all of them, or only some), before the code that answers them. It can answer the request itself or pass it on to the next one, and it sees the response on its way back. It’s used for what affects many requests, like writing them to the log, granting CORS permission or asking for a credential.Go to definition, and c, the request’s context (lesson 5).
  • HTTPException is the error Hono throws when it already knows which code applies, like the 400 for a body that isn’t JSON. In lesson 7 it came as plain text; now it comes out in JSON, with its code (error.status) and Hono’s text, meant for the client, in detail.
  • log.error(…) writes down the whole error, with its stack trace, and the request’s id.
  • c.json(…, 500) gives the client only Internal server error and the id.

Neither the message nor the stack trace of an unexpected error goes out to the client: they would show anyone your folders, libraries and versions. The 500 is enough, “I failed” (status codes), plus a number to complain with.

The id is set by a Hono middleware, requestId, which goes first:

src/app.ts
// requestId gives each request an identifier and returns it in the X-Request-Id header.
app.use(requestId());
app.use(requestLog);
app.use(cors({ origin: 'https://shop.example' }));

requestId() gives each request a random piece of text, like bf209234-574b-452c-9969-de31923346e2; if the request already carries a valid X-Request-Id header, it uses that one, so a client could repeat an id. It stores it in the context, where c.get('requestId') gets it from, and returns it in the X-Request-Id HeaderInformation a protocol puts in front of its data to do its job. In HTTP they are text lines of the form “Name: value”, such as Host or Content-Type; in TCP or IP they are numbers in fixed positions, such as ports or addresses.Go to definition.

It goes before requestLog so the log already has the id: order matters (lesson 6).

In Phase 1 you searched the practice log for 500s with grep '" 500 ', knowing the code was field 9. A Structured logA log in which each line is a list of named data, almost always in JSON, instead of a free-form sentence: {"path":"/error","status":500}. That way a program can filter by any piece of data, such as “the requests that got a 500.”Go to definition gives each piece of data a name. This is what a line of the shop’s log looks like now:

{"level":30,"time":1791890346764,"pid":177,"hostname":"laptop","requestId":"bf209234-574b-452c-9969-de31923346e2","method":"GET","path":"/error","status":500,"ms":2,"msg":"request"}

It’s written by pino, a Package (of code)Ready-to-use code that someone publishes with a name and a version number, so others can install it in their projects instead of writing it. In Node.js, packages are installed with npm and kept in the node_modules folder.Go to definition that does only this. The project creates a single log with pino(…) and uses it everywhere:

src/log.ts
// The logs, in JSON: one line per event, which a person can read and so can a program.
import { pino } from 'pino';
import { config } from './config.ts';
export const log = pino({ level: config.LOG_LEVEL });

Lesson 6’s request log wrote a sentence with console.log; now it writes data:

src/middleware/request-log.ts
import type { MiddlewareHandler } from 'hono';
import { log } from '../log.ts';
// The same idea as in lesson 6, now with pino: each request, one JSON line with its id.
export const requestLog: MiddlewareHandler = async (c, next) => {
const start = performance.now();
await next();
log.info(
{
requestId: c.get('requestId'),
method: c.req.method,
path: c.req.path,
status: c.res.status,
ms: Math.round(performance.now() - start),
},
'request',
);
};
  • log.info(data, message) writes a line of level info with the object’s data and the message in msg.
  • pino adds level, the level as a number; time, the milliseconds since 1970; pid, the process number (lesson 5 of Phase 1), and hostname, the computer.
  • An error, like the one in log.error({ err: error }), is written with its type, its message and its stack trace: type, message and stack.

Every line has a Log levelHow important a line of the log is. From least to most: trace, debug, info, warn, error and fatal. The program is given a minimum level, and it only writes the lines of that level or a higher one, so the log doesn’t fill up with details.Go to definition, and the log has a minimum: it only writes the lines of that level or a higher one.

Level Number What for
fatal 60 The program can’t go on
error 50 Something failed, like the 500 from /error
warn 40 Odd, but not a failure: a warning
info 30 The usual: startups, requests
debug 20 Details for hunting a bug while you code
trace 10 Even more detail

silent writes nothing. The minimum comes from the Environment variableA name with a value, like PORT=3000, that a program receives when it starts from whoever starts it, for example the shell. It lets you configure the program without changing its code and give it secrets without writing them in it.Go to definition LOG_LEVEL, which log.ts passes to pino as level: info day to day, debug when you’re hunting a bug and silent in the tests.

Until now, the admin token was written in the code, and a SecretA piece of data that gives access to something and that only the people and programs that need it should know, like a database password or an API key. It’s never written inside the code.Go to definition can’t live there (environment variables). Now it comes from the environment, like the port and the log level:

src/config.ts
// The configuration comes from the environment variables (Phase 1, lesson 7). It's checked at
// startup: if something is missing, the server doesn't start and says what's missing.
import { z } from 'zod';
const configSchema = z.object({
PORT: z.coerce.number().int().min(1).max(65_535).default(3000),
LOG_LEVEL: z.enum(['fatal', 'error', 'warn', 'info', 'debug', 'trace', 'silent']).default('info'),
ADMIN_TOKEN: z.string({ error: 'ADMIN_TOKEN is missing' }).min(16, 'ADMIN_TOKEN is too short'),
});
const result = configSchema.safeParse(process.env);
if (!result.success) {
for (const issue of result.error.issues) {
console.error(`Configuration: ${issue.path.join('.')}: ${issue.message}`);
}
process.exit(1);
}
export const config = result.data;
  • configSchema is a Zod SchemaThe description of what some data must look like: which fields it has, whether each one is a number or text, and which values are accepted. A program compares the incoming data with it and says whether it matches or what’s wrong.Go to definition, like the ones in lesson 7, for the environment variables.
  • z.coerce.number() turns PORT into a number, because an environment variable always arrives as text; .default(3000), if there isn’t one. z.enum accepts only one of the levels.
  • ADMIN_TOKEN has no default value and is at least 16 characters long.
  • safeParse(process.env) checks everything at once. If something fails, it writes each problem with console.error, which goes to stderrStandard error, a second output channel that programs use for warnings and errors. It goes to the screen even when the normal output goes to a file or to another program.Go to definition, and process.exit(1) ends with code 1.

With parse, which throws an exception instead of returning the result, it would also end, but with a stack trace instead of a clear sentence. And it’s better to refuse to start than to fail in the middle of the night, with the first request that needs the token.

The values go in a .env file, which never goes to Git; what does go is this example:

.env.example
# Copy this file as .env and change the values. .env isn't uploaded to Git: it's in .gitignore.
PORT=3000
LOG_LEVEL=info
# A long text that's hard to guess. You can generate one with: openssl rand -hex 24
ADMIN_TOKEN=change-this-to-a-long-token

The start and dev scripts in package.json now start with node --env-file-if-exists=.env: Node reads .env if it exists, and if not, it carries on with whatever variables it has, as on a server, where systemd sets them. npm test uses --env-file=test/.env, with a test token and LOG_LEVEL=silent.

In server.ts, the port comes from config and the startup message goes through the log:

src/server.ts
import { serve } from '@hono/node-server';
import { app } from './app.ts';
import { config } from './config.ts';
import { log } from './log.ts';
serve({ fetch: app.fetch, port: config.PORT, hostname: '127.0.0.1' }, (info) => {
log.info(`The shop is listening on http://localhost:${info.port}`);
});

admin-only.ts changes one line: it compares with config.ADMIN_TOKEN.

The goal: cause an error, find it in the log with the id the client receives and work out which line of your code it’s on.

You work in your shop-api, just as you left it in lesson 7. First, install pino with its exact version:

0. Install pino

Ventana de terminal
npm install pino@10.4.0

What you will see:

added 13 packages, and audited 22 packages in 2s
2 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities

Then write the changes from above: log.ts, .env.example and test/.env are new, and app.ts, config.ts, request-log.ts, admin-only.ts, server.ts and the package.json scripts change. The outputs are from Node 26.11.1; your times, ids and dates will be different.

If you get stuck, download this lesson’s folder and compare it with yours (it also brings the new tests): from ~/backend-course/phase-3, curl -O https://backenddesdecero.com/practicas/shop-api/08-errors-and-logs.tar.gz and tar -xzf 08-errors-and-logs.tar.gz.

1. Start without configuration

Ventana de terminal
npm start

What you will see:

> shop-api@1.0.0 start
> node --env-file-if-exists=.env src/server.ts
.env not found. Continuing without it.
Configuration: ADMIN_TOKEN: ADMIN_TOKEN is missing

Node warns that there’s no .env, and config.ts finds that the token is missing. The server never gets to listen: echo $? would say 1.

2. Create your .env and a token

Ventana de terminal
cp .env.example .env
openssl rand -hex 24

What you will see:

674679605d58a679d6cd63f7d69113497cfba8acd7383e43

openssl rand -hex 24 writes 24 random bytes in hexadecimal: 48 characters nobody is going to guess. Yours will be different. Open .env in VS Code (or with nano .env) and put it after ADMIN_TOKEN=, in place of change-this-to-a-long-token.

3. Start it and save the log

Ventana de terminal
npm start --silent | tee shop.log

What you will see:

{"level":30,"time":1791890343954,"pid":177,"hostname":"laptop","msg":"The shop is listening on http://localhost:3000"}

--silent removes npm’s two lines, so the file will only contain JSON. tee copies whatever reaches it through the pipe to the screen and to shop.log (lesson 4 of Phase 1). Under hostname you’ll see your computer’s name.

If you get EADDRINUSE, you already have another server on port 3000: stop it with Ctrl + C in its terminal.

Open another terminal in the same folder and cause the error:

4. Request the route that fails

Ventana de terminal
curl -i localhost:3000/error

What you will see:

HTTP/1.1 500 Internal Server Error
content-type: application/json
vary: Origin
x-request-id: bf209234-574b-452c-9969-de31923346e2
content-length: 84
Date: Tue, 13 Oct 2026 11:19:06 GMT
Connection: keep-alive
Keep-Alive: timeout=5
{"error":"Internal server error","requestId":"bf209234-574b-452c-9969-de31923346e2"}

That’s everything the client sees: the 500, a message and the id, also in x-request-id. No sign of the stack trace. With curl -i localhost:3000/offers you’ll see the 404 from notFound.

And now, the cut-off order from the beginning:

5. A body that isn't JSON

Ventana de terminal
curl -i localhost:3000/orders -H 'Content-Type: application/json' -d '{"productId": 1, "quantity": '

What you will see:

HTTP/1.1 400 Bad Request
content-type: application/json
vary: Origin
x-request-id: 006ee57f-4f84-4f54-ae48-a0ded69968f5
content-length: 80
Date: Tue, 13 Oct 2026 11:19:07 GMT
Connection: keep-alive
Keep-Alive: timeout=5
{"error":"The request cannot be read","detail":"Malformed JSON in request body"}

Lesson 7’s 400, now in JSON: it’s an HTTPException. The failure is the client’s, so it leaves no stack trace in the log.

In the first terminal, one line has appeared per request, plus one more for the 500. Find the ones for /error by their id with the grep from lesson 2 of Phase 1 (with your id, not the one here):

6. Everything that happened in that request

Ventana de terminal
grep bf209234 shop.log

What you will see:

{"level":50,"time":1791890346762,"pid":177,"hostname":"laptop","err":{"type":"Error","message":"Something failed on purpose","stack":"Error: Something failed on purpose\n at file:///Users/ana/backend-course/phase-3/shop-api/src/app.ts:50:9\n at dispatch (file:///Users/ana/backend-course/phase-3/shop-api/node_modules/hono/dist/compose.js:35:17)\n at file:///Users/ana/backend-course/phase-3/shop-api/node_modules/hono/dist/compose.js:35:40\n at cors (file:///Users/ana/backend-course/phase-3/shop-api/node_modules/hono/dist/middleware/cors/index.js:103:9)\n at async dispatch (file:///Users/ana/backend-course/phase-3/shop-api/node_modules/hono/dist/compose.js:35:11)\n at async requestLog (file:///Users/ana/backend-course/phase-3/shop-api/src/middleware/request-log.ts:7:3)\n at async dispatch (file:///Users/ana/backend-course/phase-3/shop-api/node_modules/hono/dist/compose.js:35:11)\n at async requestId (file:///Users/ana/backend-course/phase-3/shop-api/node_modules/hono/dist/middleware/request-id/request-id.js:30:3)\n at async dispatch (file:///Users/ana/backend-course/phase-3/shop-api/node_modules/hono/dist/compose.js:35:11)\n at async file:///Users/ana/backend-course/phase-3/shop-api/node_modules/hono/dist/hono-base.js:287:21"},"requestId":"bf209234-574b-452c-9969-de31923346e2","msg":"uncaught error"}
{"level":30,"time":1791890346764,"pid":177,"hostname":"laptop","requestId":"bf209234-574b-452c-9969-de31923346e2","method":"GET","path":"/error","status":500,"ms":2,"msg":"request"}

Two lines with the same id: the one from log.error, level 50, with the stack trace in err, and the one from the request log, level 30, with the 500.

grep searches for text. To ask about a piece of data, like “status of 500 or more,” you need a program that understands JSON: jq. Recent Macs come with it; if jq --version says command not found, install it (brew install jq on a Mac, sudo apt install jq on Linux and WSL).

7. Ask the log with jq

Ventana de terminal
jq -c 'select(.status >= 500)' shop.log
jq -r 'select(.level == 50) | .err.stack' shop.log

What you will see:

{"level":30,"time":1791890346764,"pid":177,"hostname":"laptop","requestId":"bf209234-574b-452c-9969-de31923346e2","method":"GET","path":"/error","status":500,"ms":2,"msg":"request"}
Error: Something failed on purpose
at file:///Users/ana/backend-course/phase-3/shop-api/src/app.ts:50:9
at dispatch (file:///Users/ana/backend-course/phase-3/shop-api/node_modules/hono/dist/compose.js:35:17)
at file:///Users/ana/backend-course/phase-3/shop-api/node_modules/hono/dist/compose.js:35:40
at cors (file:///Users/ana/backend-course/phase-3/shop-api/node_modules/hono/dist/middleware/cors/index.js:103:9)
at async dispatch (file:///Users/ana/backend-course/phase-3/shop-api/node_modules/hono/dist/compose.js:35:11)
at async requestLog (file:///Users/ana/backend-course/phase-3/shop-api/src/middleware/request-log.ts:7:3)
at async dispatch (file:///Users/ana/backend-course/phase-3/shop-api/node_modules/hono/dist/compose.js:35:11)
at async requestId (file:///Users/ana/backend-course/phase-3/shop-api/node_modules/hono/dist/middleware/request-id/request-id.js:30:3)
at async dispatch (file:///Users/ana/backend-course/phase-3/shop-api/node_modules/hono/dist/compose.js:35:11)
at async file:///Users/ana/backend-course/phase-3/shop-api/node_modules/hono/dist/hono-base.js:287:21

select(…) lets through the lines that meet the condition, and -c writes each on one line. The second command keeps the level 50 lines and pulls out their stack trace (.err.stack); -r writes it as text, with its line breaks.

The first line of the stack trace answers the goal: src/app.ts:50:9, the throw in /error (in your file, the line may be a different one). The node_modules/hono lines are the layers the request went through, your requestLog among them.

Now, turn down the volume. Stop the server with Ctrl + C, start it with another level and, in the second terminal, repeat curl -s localhost:3000/products/2 and curl -s localhost:3000/error:

8. Only warnings and errors

Ventana de terminal
LOG_LEVEL=warn npm start --silent

What you will see:

{"level":50,"time":1791890352236,"pid":215,"hostname":"laptop","err":{"type":"Error","message":"Something failed on purpose","stack":"Error: Something failed on purpose\n at file:///Users/ana/backend-course/phase-3/shop-api/src/app.ts:50:9\n at dispatch (file:///Users/ana/backend-course/phase-3/shop-api/node_modules/hono/dist/compose.js:35:17)\n at file:///Users/ana/backend-course/phase-3/shop-api/node_modules/hono/dist/compose.js:35:40\n at cors (file:///Users/ana/backend-course/phase-3/shop-api/node_modules/hono/dist/middleware/cors/index.js:103:9)\n at async dispatch (file:///Users/ana/backend-course/phase-3/shop-api/node_modules/hono/dist/compose.js:35:11)\n at async requestLog (file:///Users/ana/backend-course/phase-3/shop-api/src/middleware/request-log.ts:7:3)\n at async dispatch (file:///Users/ana/backend-course/phase-3/shop-api/node_modules/hono/dist/compose.js:35:11)\n at async requestId (file:///Users/ana/backend-course/phase-3/shop-api/node_modules/hono/dist/middleware/request-id/request-id.js:30:3)\n at async dispatch (file:///Users/ana/backend-course/phase-3/shop-api/node_modules/hono/dist/compose.js:35:11)\n at async file:///Users/ana/backend-course/phase-3/shop-api/node_modules/hono/dist/hono-base.js:287:21"},"requestId":"c9da317d-8965-4cdc-82dd-8a7472321831","msg":"uncaught error"}

Nothing shows up at startup, because “The shop is listening” is info, like the request lines: only the error one is left. LOG_LEVEL=warn in front of the command sets the variable for that program only, and it wins over the one in .env: Node doesn’t change a variable that already exists.

Challenge: the project doesn’t write anything at debug level yet. Add a debug line in GET /products, after reading max, and find out which LOG_LEVEL makes it show up.Show answer

Add this line below const { max } = c.req.valid('query');:

log.debug({ max }, 'price filter');

Start with LOG_LEVEL=debug npm start --silent and request curl -s 'localhost:3000/products?max=10'. The level 20 line shows up in the log before the request’s line:

{"level":30,"time":1791890354479,"pid":247,"hostname":"laptop","msg":"The shop is listening on http://localhost:3000"}
{"level":20,"time":1791890357262,"pid":247,"hostname":"laptop","max":10,"msg":"price filter"}
{"level":30,"time":1791890357264,"pid":247,"hostname":"laptop","requestId":"e809e977-66b8-4228-bbf5-3002124bbabd","method":"GET","path":"/products","status":200,"ms":4,"msg":"request"}

With npm start --silent, which uses the info from .env, only the first and the last show up. The debug line stays in the code without getting in the way, for when you need it. When you’re done, you can delete it. shop.log can stay: the *.log in .gitignore keeps it out of Git.

  • Error pages with a code. “Something went wrong. Reference: 7F3A…”: that’s your request’s id, the one support looks up in their log.
  • The cf-ray header from backenddesdecero.com, in lesson 4 of Phase 2, is the id Cloudflare gives each request; GitHub uses x-github-request-id. They’re in DevTools, in the response headers.
  • The DevTools console shows a page’s errors with their stack trace, like the one from crash.ts.
  • Sending the client the message or the stack trace of an unexpected error. You’re showing your code to anyone. For the client, a fixed message and the id; everything else, to the log.
  • An empty catch. catch {} makes the error disappear: nobody finds out. If you catch an error, at least write it in the log.
  • Forgetting the await. The try ends before the error arrives, and in a server that uncaught error can bring the process down.
  • Writing secrets in the log. A log is stored, copied and read by many people: never the Authorization header, a token or a password.
  • throw throws an error and try/catch catches it; with async, only if you wait for it with await. An error nobody catches ends the program with code 1.
  • Hono catches the errors of each request. With onError, the client gets a 500 with no stack trace and with an id (also in X-Request-Id), and the log gets the stack trace with that id.
  • A structured log is one JSON line per event: you read it, filter it with grep and ask it questions with jq.
  • LOG_LEVEL sets the minimum level: info day to day, debug to hunt a bug and silent in the tests.
  • The configuration comes from environment variables and is checked with Zod at startup: if something is missing, the server doesn’t start and says why.
A customer writes: “when I paid I got Internal server error and the code 2ccc958e…” What do you do first?

In a script, you call loadOrder(7) inside a try, without await. loadOrder is async and throws an error. What happens?

A teammate suggests that the shop’s 500 include error.message and the stack trace, to debug faster. What do you tell them?

The shop starts with LOG_LEVEL=warn. One route writes log.info and another, log.error. Which lines reach the log?

You put this lesson’s API on a server and forget to set ADMIN_TOKEN. What happens?

You want to know which of yesterday’s requests took longer than 500 ms. With which log can you ask that in a single command?

phase-3 · lesson 8/9