6
votes

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`)
    );
2
Does mongoose.connect return promise?Julian Liu
@pindev yes it doesdevpato
The error means that you should add .catch() to promises. i.e mongoose.connect(...).catch(err => console.log(err))Julian Liu
@pindev that works! add it as an answer so you get your pointsdevpato

2 Answers

5
votes

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.

4
votes

UnhandledPromiseRejectionWarning means that promises should have .catch() like

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