0
0
Expressframework~5 mins

Synchronous error handling in Express

Choose your learning style9 modes available
Introduction

Synchronous error handling helps catch mistakes that happen right away in your code. It stops the app from crashing and shows a clear message.

When you want to catch errors from code that runs immediately inside a route.
When you need to handle mistakes like missing variables or wrong data types in your request.
When you want to send a friendly error message back to the user if something goes wrong.
When debugging your app to find where it breaks in synchronous code.
When you want to keep your server running even if a route has a problem.
Syntax
Express
app.get('/route', (req, res, next) => {
  try {
    // code that might throw an error
  } catch (err) {
    next(err); // pass error to Express error handler
  }
});

Use try...catch to catch errors in synchronous code.

Call next(err) to send the error to Express's error handler middleware.

Examples
This example checks if a name is given in the query. If not, it throws an error caught by try...catch.
Express
app.get('/hello', (req, res, next) => {
  try {
    if (!req.query.name) throw new Error('Name is required');
    res.send(`Hello, ${req.query.name}!`);
  } catch (err) {
    next(err);
  }
});
This example handles division and throws an error if dividing by zero.
Express
app.get('/divide', (req, res, next) => {
  try {
    const a = Number(req.query.a);
    const b = Number(req.query.b);
    if (b === 0) throw new Error('Cannot divide by zero');
    res.send(`Result: ${a / b}`);
  } catch (err) {
    next(err);
  }
});
Sample Program

This Express app has a route /greet that requires a name query parameter. If missing, it throws an error caught by try...catch and passed to the error handler middleware. The error handler sends a 400 status with the error message as JSON.

Express
import express from 'express';
const app = express();

app.get('/greet', (req, res, next) => {
  try {
    const name = req.query.name;
    if (!name) throw new Error('Missing name parameter');
    res.send(`Hello, ${name}!`);
  } catch (err) {
    next(err);
  }
});

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

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

Always use next(err) inside catch to let Express handle the error properly.

Errors thrown outside try...catch in synchronous code will crash the app if not handled.

For asynchronous code, use different error handling methods (like async/await with try...catch or error middleware).

Summary

Synchronous errors happen immediately and can be caught with try...catch.

Use next(err) to pass errors to Express error handlers.

This keeps your app stable and user-friendly by showing clear error messages.