Asynchronous Error Handling in Express

·

3 min read

Step-1 : Configuration

mkdir my-blog-app
cd my-blog-app
npm init -y
npm install express mongoose morgan express-async-handler

In this example, we'll use Mongoose as our ORM and Morgan for logging.

Step-2 : Connecting to MongoDB

  • Set up the database connection: Create a db.js file in your project directory to set up the database connection:

      const mongoose = require('mongoose');
    
      const connectDB = async () => {
        try {
          const conn = await mongoose.connect('mongodb://localhost/my-blog-app', {
            useNewUrlParser: true,
            useUnifiedTopology: true,
            useFindAndModify: false,
            useCreateIndex: true,
          });
          console.log(`MongoDB Connected: ${conn.connection.host}`);
        } catch (err) {
          console.error(err);
          process.exit(1);
        }
      };
    
      module.exports = connectDB;
    

    This file exports a function that connects to a local MongoDB database. We're using the mongoose.connect() method to establish the connection and logging the status of the connection in the console.

Step-3 : Defining the Blog schema.

  • Define the blog model: Create a models/Blog.js file to define the blog model:

      const mongoose = require('mongoose');
    
      const blogSchema = new mongoose.Schema({
        title: {
          type: String,
          required: true,
        },
        body: {
          type: String,
          required: true,
        },
        author: {
          type: String,
          required: true,
        },
        createdAt: {
          type: Date,
          default: Date.now,
        },
        updatedAt: {
          type: Date,
          default: Date.now,
        },
      });
    
      const Blog = mongoose.model('Blog', blogSchema);
    
      module.exports = Blog;
    

    This file exports a Mongoose model for the blog posts. We're defining a schema with fields for the blog post title, body, author, and timestamps for creation and update dates.

  • Set up the Express app: Create an app.js file in your project directory to set up the Express app:

      const express = require('express');
      const morgan = require('morgan');
      const connectDB = require('./db');
      const asyncHandler = require('express-async-handler');
      const Blog = require('./models/Blog');
    
      // Connect to the database
      connectDB();
    
      const app = express();
    
      // Logging middleware
      app.use(morgan('dev'));
    
      // Body parsing middleware
      app.use(express.json());
    
      // GET /blogs route handler
      app.get(
        '/blogs',
      /*
      We are importing thhe asyncHandler and passing our logic as a function as the argument.
      */
      As simple as that :)
        asyncHandler(async (req, res) => {
          const blogs = await Blog.find();
          res.json(blogs);
        })
      );
    
      // Error handler middleware
      app.use((err, req, res, next) => {
        console.error(err.stack);
        res.status(500).send('Internal Server Error');
      });
    
      // Start the server
      app.listen(3000, () => {
        console.log('Server listening on port 3000');
      });
    

    This file sets up the Express app and defines a GET route handler for fetching all blog posts. We're using express-async-handler to handle async errors in the route handler. If an error occurs, it will be passed to the error handler middleware.

  • Start the server: Start the server by running the following command:

To start the server, run the following command in the terminal:

node app.js

This will start the server on port 3000, and you can access it in your web browser by navigating to http://localhost:3000/blogs. If there are any errors in your code, you should see them printed in the console.

Did you find this article valuable?

Support The Backend Express by becoming a sponsor. Any amount is appreciated!