Async errors without crashes
Await every promise and make failure an explicit path.
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.
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
EasyTurn a rejection into a 500
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 inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.