Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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`)
    );
like image 812
Patricio Vargas Avatar asked Jun 05 '19 17:06

Patricio Vargas


People also ask

How do you handle unhandled rejection in node JS?

To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) (node:31727) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated.

How do you handle unhandled promise rejection?

If an error condition arises inside a promise, you β€œreject” the promise by calling the reject() function with an error. To handle a promise rejection, you pass a callback to the catch() function. This is a simple example, so catching the rejection is trivial.

What happens on unhandled promise rejection?

The unhandledrejection event is sent to the global scope of a script when a JavaScript Promise that has no rejection handler is rejected; typically, this is the window , but may also be a Worker .

How do you handle reject In await?

Handling rejected promises You can handle rejected promises without a try block by chaining a catch() handler before awaiting the promise.


1 Answers

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.

like image 109
Ashot Avatar answered Oct 15 '22 05:10

Ashot