Unhandled promise rejection. This error originated either by throwing inside of an async function – NodeJS

I’m very new with NodeJS. I’m trying to create a simple server that has a connection to my mongoDB Atlas database but when I run my server I get this error:

UnhandledPromiseRejectionWarning: Unhandled promise rejection. This
error originated either by throwing inside of an async function
without a catch block, or by rejecting a promise which was not
handled with .catch(). (rejection id: 1) (node:8825) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In
the future, promise rejections that are not handled will terminate the
Node.js process with a non-zero exit code.

Seems to be a common problem based on what I googled, I added the try/catch but it still isn’t working.

'use strict';
    //const AWS = require('aws-sdk');
    const express = require('express');
    const mongoose = require('mongoose');
    const uuidv4 = require('uuid/v4');

    //exports.handler = (event, context, callback) => {
    mongoose.connect(
      'mongodb+srv://xxxx:[email protected]/test?retryWrites=true',
      {
        useNewUrlParser: true
      }
    ),
      () => {
        try {
          //something
        } catch (error) {
          console.error(error);
        }
      };
    const connection = mongoose.connection;

    connection.once('open', () => {
      console.log('🖥 Connection to DB was succesful');
    });

    const app = express();
    app.listen({ port: 4800 }, () =>
      console.log(`🚀 Server ready at http://localhost:4800`)
    );

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Mongoose connect returns promise, and most probably there is an error when it attempts to connect: I would suggest using the async function, to handle DB connection. Here is what I use currently.

const config = require('config').db; // Your DB configuration 
const combineDbURI = () => {
   return `${config.base}${config.host}:${config.port}/${config.name}`;
};

// Connecting to the database
const connect = async function () {
  const uri = combineDbURI(); // Will return DB URI 
  console.log(`Connecting to DB - uri: ${uri}`);
  return mongoose.connect(uri, {useNewUrlParser: true});
};

And then call it within an async function using await:

 (async () => {
   try {
    const connected = await connect();
   } catch(e) {
    console.log('Error happend while connecting to the DB: ', e.message)
   }
 })();

Or you can call without await using promise API:

 connect().then(() => {
    console.log('handle success here');
 }).catch((e) => {
    console.log('handle error here: ', e.message)
 })

Besides, using try catch when using callbacks does not make sense, when you don’t have promises, you should use error callbacks to catch errors.

So to answer your question (as others mentioned in the comments):

As connect function returns a promise, you should use catch callback to catch the promise rejection. Otherwise, it will throw Unhandled Promise Rejection.

I hope this will help.

Solution 2

UnhandledPromiseRejectionWarning means that promises should have .catch() like

mongoose.connect(...).catch(err => console.log(err))

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply