Synchronous error handling helps catch mistakes that happen right away in your code. It stops the app from crashing and shows a clear message.
Synchronous error handling in 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.
try...catch.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); } });
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); } });
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.
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'); });
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).
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.