Node.js Foundations·From script to service

Async errors without crashes

Await every promise and make failure an explicit path.

Intermediate 13 min read Lesson 9 of 300 Challenge included
What you will be able to do
  • Wrap async handlers so rejected promises reach the error middleware.
  • Return generic messages to clients and detailed context to logs.
  • Handle SIGTERM to finish in-flight work before exit.

In plain English

An async route must catch its own errors or hand them to a wrapper. Validate input early, use typed error codes and log context without logging secrets. Process-level handlers are a last resort, not a recovery strategy.

async-wrapper.jsJavaScript
function asyncRoute(handler) {
  return (request, response, next) => {
    Promise.resolve(handler(request, response, next)).catch(next)
  }
}

app.get('/api/courses', asyncRoute(async (_request, response) => {
  const courses = await db.course.findMany({ where: { published: true } })
  response.json(courses)
}))
Your turn

Turn a rejection into a 500

Easy

Call an async function, catch a thrown error and respond with 500 and a generic error body.

JS · starter
app.get('/api/courses', async (request, response) => {
  const courses = await loadCourses()
})
Check your understanding before moving on.
Knowledge checkQuestion 1

Why wrap an async Express handler?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Lesson 9 of 300 · 0% of course