Setup Error Middleware and async Handler in Node.js

Aneeqa Khan - Dec 5 '22 - - Dev Community

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.

For this series, I'm following an excellent video tutorial from Traversy Media

Table Of Contents

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,
};


Enter fullscreen mode Exit fullscreen mode

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



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

app.use(errorHandler);
...


Enter fullscreen mode Exit fullscreen mode

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'})
}


Enter fullscreen mode Exit fullscreen mode

and I'll get this error response

error-handling

Implement asyncHandler

As I am going to use mongoose in my next blog to interact with the database, which returns a promise in response. So to handle this I'll use async/await in all of the todosController functions.

For async/await we have to use a try/catch method but as I already have an error handler so I'll use express-async-handler package.
This package will handle the exceptions inside of async express routes and pass them to my express error handlers.

Install async handler with this command



npm i express-async-handler


Enter fullscreen mode Exit fullscreen mode

Now use it like this for all functions in todosController.js



const asyncHanlder = require('express-async-handler');

const getTodos = asyncHanlder(async (req, res) => {
  res.status(200).json({message: 'Get todos'})
});

...


Enter fullscreen mode Exit fullscreen mode

In the next blog, I'll create a database in MongoDB and connect it with Mongoose.

Thank you for reading!
Feel free to connect on Twitter

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .