Member-only story

Setup Error Middleware and async Handler in Node.js— Part 3

Aneeqa Khan
2 min readDec 5, 2022

The express framework has a default error handler, that catches and processes errors that occur synchronously and asynchronously.

But the express default error handler returns an error in the HTML page. To fix this, I’ll add an error middleware in my app.

Implement errorMiddleware

Create a file named as errorMiddleware.js in /backend/middleware folder and add this code.

const errorHandler = (err, req, res, next) => {
const statusCode = res.statusCode ? res.statusCode : 500;
res.status(statusCode);
res.json({
message: err.message,
stack: err.stack,
});
};
module.exports = {
errorHandler,
};

and now I’ll add it into server.js file.

const { errorHandler } = require('./middleware/errorMiddleware');
...
app.use(errorHandler);
...

Make sure to define error-handling middleware in the last, after other app.use().
You can read more about it here

Now I’ll test the errorMiddleware in my setTodo POST call

const setTodo = (req, res) => {
if (!req.body.text) {
res.status(400);
throw new Error('Please add text field');
}
res.status(200).json({message: 'Set todo'})
}

--

--

Aneeqa Khan
Aneeqa Khan

Written by Aneeqa Khan

I’m a frontend web and mobile developer specialized in web/mobile designs and frontend frameworks. I usually work with React, React Native, Next and TypeScript.

No responses yet