0
0
Expressframework~5 mins

Async error handling in routes in Express

Choose your learning style9 modes available
Introduction

Async error handling helps catch problems in routes that use asynchronous code, so your app doesn't crash and can respond properly.

When your route handler uses async/await to fetch data from a database.
When calling external APIs inside a route that might fail.
When performing file operations asynchronously in a route.
When you want to keep your app stable by catching errors in async code.
When you want to send meaningful error messages to users if something goes wrong.
Syntax
Express
app.get('/route', async (req, res, next) => {
  try {
    // async code here
    res.send(result);
  } catch (error) {
    next(error); // pass error to Express error handler
  }
});

Use try/catch inside async route handlers to catch errors.

Call next(error) to let Express handle the error properly.

Examples
Fetch a user asynchronously and handle errors by passing them to Express.
Express
app.get('/user/:id', async (req, res, next) => {
  try {
    const user = await getUserById(req.params.id);
    res.json(user);
  } catch (err) {
    next(err);
  }
});
Save data asynchronously and send a 201 status on success, or pass errors on failure.
Express
app.post('/data', async (req, res, next) => {
  try {
    const saved = await saveData(req.body);
    res.status(201).send(saved);
  } catch (error) {
    next(error);
  }
});
Sample Program

This Express app has a route that fetches data asynchronously. If the ID is '0', it throws an error. The error is caught and passed to the error handler, which sends a 500 status with the error message.

Express
import express from 'express';
const app = express();
app.use(express.json());

// Simulated async function that may throw
async function fetchData(id) {
  if (id === '0') throw new Error('Invalid ID');
  return { id, name: 'Item ' + id };
}

app.get('/item/:id', async (req, res, next) => {
  try {
    const data = await fetchData(req.params.id);
    res.json(data);
  } catch (error) {
    next(error);
  }
});

// Error handler middleware
app.use((err, req, res, next) => {
  res.status(500).json({ error: err.message });
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

Always use next(error) in async routes to avoid unhandled promise rejections.

Express error handler middleware must have four parameters: (err, req, res, next).

Without proper async error handling, your server might crash or hang on errors.

Summary

Use try/catch blocks in async route handlers to catch errors.

Pass errors to Express with next(error) for centralized handling.

Set up an error handler middleware to send user-friendly error responses.