Isak La Fleur
Isak La Fleur

Reputation: 4668

Why I get UnhandledPromiseRejectionWarning: Unhandled promise rejection?

Script runs until it tries to close the connection of the database, and now it gives me a promise error.

When I comment out this section, the scripts runs fine without error, but of course, the db connections never closes...

>     // .then(() => {
>     //   database.close();
>     // }, err => {
>     //   return database.close().then(() => {throw err; });
>     // })

Is it not enough to have ONE catch block in the end of the promise chain?

I get the following error:

[ERROR] (node:9376) 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) [[09:33:03.101]] [ERROR] (node:9376) [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.

mysql.js

const mysql = require("mysql");

const mySQLConnectionDetails = {
  host: "localhost",
  user: "xxxx",
  password: "xxxx",
  database: "amdm",
  multipleStatements: true
};

class Database {
  constructor(config) {
    this.connection = mysql.createConnection(config);
  }
  query(sql, args) {
    return new Promise((resolve, reject) => {
      this.connection.query(sql, args, (err, rows) => {
        if (err)
          return reject(err);
        resolve(rows);
      });
    });
  }
  close() {
    return new Promise((resolve, reject) => {
      this.connection.end(err => {
        if (err)
          return reject(err);
        resolve();
      });
    });
  }
}
module.exports = { Database, mySQLConnectionDetails };

index.js

require("console-stamp")(console, "[HH:MM:ss.l]");
const express = require("express");
const router = express.Router();
const { Database, mySQLConnectionDetails} = require("../helpers/mySQL");
const { cleanseString, cleanseStringToArray, generateCountDuplication, sortValuesBykey, generateScoreArray, calculateAverage, replaceAbbreviationWithExpansion } = require("../helpers/stringFixers");

const database = new Database(mySQLConnectionDetails);


/* GET Clean original name of part and store it in database. */
router.get("/createcleanname", (req, res) => {
  let allParts = [];
  let eClassCodes = []; // here I define eClassCodes
  let abbreviationsAndExpansions = [];


  database.query("SELECT * FROM partnumbersclassified")
    .then(rows => {
      console.log(rows.length);
      allParts = rows;
      return database.query("SELECT * FROM amdm.abbreviationexpansion");
    })
    .then(rows => {
      abbreviationsAndExpansions = rows;
      return database.query("SELECT * FROM eclasstree WHERE numberofdigits = '8'");
    })
    .then(rows => {
      eClassCodes = rows; // Here I assign the values to the variable.
      const replaceAbbreviations = replaceAbbreviationWithExpansion(allParts, abbreviationsAndExpansions);
      console.log("replaceAbbreviations finished");
      const cleanseStrings = cleanseString(replaceAbbreviations, "cleanname");
      console.log("cleanseStrings finished");
      return cleanseStrings;
    })
    .then(result => {
      result.forEach(obj => {
        return database.query(`UPDATE partnumbersclassified SET cleanname = '${obj.cleanname}' WHERE itemnumber = '${obj.itemnumber}'`);
      });
      console.log("cleanname updated on all parts");
    })
    .then(() => {
      database.close();
    }, err => {
      return database.close().then(() => {throw err; });
    })
    .catch(err => {throw err;});
});

Upvotes: 0

Views: 1798

Answers (1)

jro
jro

Reputation: 940

Instead of throwing the error in catch, do what it was intended for: handle the error.

In your case, you may want to simply log the error.

.then(() => {
    database.close();
  }, err => {
    return database.close().then(() => {throw err; });
  })
  .catch(err => {
    console.log(err)
  })

In production environments, you may want to use an error tracker like Sentry to log and deal with errors.

Upvotes: 1

Related Questions