Skip to content

L14 Middleware and error paths

20 minSuggested first: L13 HTTP and routing

Outcome

Trace entry, handler, and return steps through a middleware chain and identify what a short circuit skips.

Learn

Middleware wraps or precedes a handler. In this example, next() enters the rest of the chain, and code after it runs on the way back out. A middleware can return a response without calling next at all.

If downstream work throws, an ordinary statement after the await is skipped unless the error is caught or the statement is in a finally block.

Worked example

Write down the log for an allowed request, then for a denied one.

A toy middleware chainText
outer: log outer-in; await next(); log outer-out
auth:  log auth-in; if denied, return response
       otherwise await next(); log auth-out
route: log handler; return response
Predict first, then show the worked explanation

Allowed: outer-in, auth-in, handler, auth-out, outer-out. Denied: auth returns early, so only outer-in, auth-in, outer-out is logged. This assumes the outer middleware receives the returned response normally.

Practice and check

Guided practice

Practice, not scored

For the denied request, which stage never starts?

Choose one answer

Exit check

Counts toward completion

The handler throws, and neither middleware catches it. Which ordinary post-next log runs?

Choose one answer

Common mistake

Reading a framework diagram as an exact error policy. Check where the implementation catches errors and whether it turns them into responses before unwinding.

Practice on a real repository

Try the first puzzle below; later, compare a response post-processing question in the second.

Related topics: Middleware and hooks, Errors

Practice is optional. Solving a puzzle doesn't complete a lesson, and lessons never change a puzzle's points.

References