In this lesson, you followed errors through a copy of the wall’s API to see which ones Express catches, where it takes them, and which ones it never sees.
Key Points
- Express catches an error thrown while it calls your function. For problem 42,
store.get()threw aNotFoundErrorbefore theGET /problems/:idhandler’s own check could run, and curl got Express’s HTML page with a500. - An error skips every ordinary function. Express stops the request’s walk and carries the error down the rest of the list. Ordinary middleware and handlers take at most three parameters, and the error passes all of them, even a function that would run for every path.
- It stops at the first function with four parameters, the error first. With none in the app, the error falls to the bottom of the list, where Express’s default handler sends its HTML page. With the toy
traceError()registered below the routers, problem 42 got the table’s404withproblem_not_found, and the server’s terminal showed the linetraceError()logged. - Express 5 forwards a rejected promise from an async handler. The
POST /problemshandler has nocatchblock either. A second Chalk Dust madestore.create()reject with aConflictError. The handler awaited it, so its own promise rejected, and Express sent the error down the same path, so curl got409withproblem_exists. - Older code wraps every async handler for Express 4. You’ll often see
tryandcatch, or a helper, around every async handler, only to pass errors on. Express 4 needed that, and Express 5 doesn’t. - A function can put an error on the path itself by calling
next()with the error. - A throw in a timer callback escapes. Express takes an error in three ways: a throw while it calls your function, a rejection of the promise your function returns, even a late one, or
next()with the error. Athrow new Error("Thrown later")inside asetTimeout()callback is none of those. The duplicate still got its409fromtraceError(). Then nothing caught the timer’s error, so Node stopped the server and the next request couldn’t connect. - A rejected promise that’s neither awaited nor returned escapes too. Without
awaitonstore.create(), TypeScript’s check complained, but Node ran the file anyway. The handler sent the pending promise, which has no fields to turn into JSON, so curl got201with an empty object,{}, and the client was told the create worked. It didn’t. The promise had rejected with theConflictError, and nothing was saved. Nobody was listening, so the server stopped again.
A throw while Express calls your function, a rejection of the promise it returns, and next() with an error all skip the ordinary functions and reach the four-parameter function after the routes. A throw in a timer, or a rejected promise nobody awaits or returns, reaches nothing, and the server stops. So await or return every promise.