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.
Practice
Solution
Step 1: Understand synchronous error handling
Synchronous errors happen immediately and can be caught with try...catch blocks.Step 2: Pass error to Express error handler
Inside catch, call next(error) to forward the error to Express's error middleware.Final Answer:
Use a try...catch block and call next(error) inside catch -> Option DQuick Check:
try...catch + next(error) = A [OK]
- Not using try...catch for synchronous errors
- Calling next() without an error object
- Using async/await without try...catch for sync errors
Solution
Step 1: Identify how to forward errors in Express
Express expects errors to be passed to next() as an argument to trigger error middleware.Step 2: Check syntax correctness
Calling next(new Error('...')) correctly passes the error object to Express.Final Answer:
next(new Error('Something went wrong')) -> Option AQuick Check:
next(error) syntax = B [OK]
- Throwing error without try...catch in sync code
- Sending error object in response instead of next()
- Logging error without forwarding it
app.get('/test', (req, res, next) => {
try {
throw new Error('Fail');
} catch (err) {
next(err);
}
});
app.use((err, req, res, next) => {
res.status(500).send(err.message);
});Solution
Step 1: Analyze error throwing and catching
The route throws an error inside try, caught immediately, then passed to next(err).Step 2: Understand error middleware response
The error middleware sends a 500 status with the error message 'Fail' to the client.Final Answer:
The client receives a 500 status with message 'Fail' -> Option CQuick Check:
next(err) triggers error middleware = A [OK]
- Assuming error crashes server without middleware
- Expecting 200 status despite error
- Confusing error middleware with normal middleware
app.get('/error', (req, res, next) => {
throw new Error('Oops');
next();
});Solution
Step 1: Check error throwing without try...catch
The error is thrown synchronously but not caught, so Express cannot handle it properly.Step 2: Understand consequence of uncaught error
Without try...catch and calling next(err), the server may crash or not handle error gracefully.Final Answer:
Error is thrown but not caught or passed to next() -> Option BQuick Check:
Throw without catch + next(err) = D [OK]
- Throwing error without try...catch
- Calling next() after throw (unreachable code)
- Assuming Express auto-catches thrown errors
Solution
Step 1: Recognize repetitive try...catch problem
Wrapping every route in try...catch is repetitive and cluttered.Step 2: Use a wrapper function to centralize error catching
A wrapper function can run the route handler and catch sync errors, forwarding them with next(err).Final Answer:
Create a wrapper function that catches errors and calls next(err) -> Option AQuick Check:
Wrapper function for sync error handling = C [OK]
- Trying to delay errors with setTimeout
- Ignoring errors by ending response early
- Using global variables for error handling
Ready to prove it?
Pass the test and this pattern moves unknown
