I'm facing a problem with error handling in NodeJS,
While I was testing an application that I made, I noticed that if I passed undefined by mistake to the mongoose.connect() it will give you an error, unfortunately, this error is not being caught by the callback function, not either by try & catch blocks:
const envVariable = undefined;
try {
mongoose.connect(envVariable, (err) => {
if (err) return console.log("There was an error");
console.log("success");
});
} catch (error) {
console.log("Hah! I caught you");
}
You see the error is not being caught, see the output:
(node:36807) UnhandledPromiseRejectionWarning: MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.
at NativeConnection.Connection.openUri (.../nodeJS/tests/node_modules/mongoose/lib/connection.js:680:11)
at .../nodeJS/tests/node_modules/mongoose/lib/index.js:345:10
at .../nodeJS/tests/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:5
at new Promise (<anonymous>)
at promiseOrCallback (.../nodeJS/tests/node_modules/mongoose/lib/helpers/promiseOrCallback.js:30:10)
at Mongoose._promiseOrCallback (.../nodeJS/tests/node_modules/mongoose/lib/index.js:1135:10)
at Mongoose.connect (.../nodeJS/tests/node_modules/mongoose/lib/index.js:344:20)
at Object.<anonymous> (.../nodeJS/tests/server.js:8:12)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47
(Use `node --trace-warnings ...` to show where the warning was created)
(node:36807) 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(). 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:36807) [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.
I've faced these kinds of problems many times in my application, but this time I caught one here to open the discussion, how can I stop these kinds of errors to show in my face? and instead, handle them in a nice way?
handle = to catch when this problem happens, and to send a nice response to the client that there was a problem from the server side.
The moongoose.connect function takes the callback as its third argument, after connection string and options object. It returns a promise, which is getting rejected on the error, but you are never handling that.
The proper syntax is either
try {
await mongoose.connect(envVariable);
console.log("success");
} catch (error) {
console.log("Hah! I caught you");
}
or
mongoose.connect(envVariable).then(() => {
console.log("success");
}, (err) => {
console.log("Hah! I caught you");
});
Related
I've tried several times to work this and I don't understand the error, I am receiving but I'll explain what I'm trying to do: Basically I want to log the messages from one channel and paste those messages onto a different channel. Here is the code I have so far;
client.on(`message`, message => {
if (message.author.bot) return; // If the message is by a bot return.
if (!message.guild) return; // If the message isn't in a guild return.
if (message.guild) {
const msgLog = `[MESSAGE] [${message.guild.name}] [#${message.channel.name}] ${message.author.username}#${message.author.discriminator}: ${message.content}\n` // You can change this to whatever you want.
client.channels.get(`814685640088223795`).send(msgLog); // Replace CHANNEL ID with the channel ID you want the logs to go to.
return;
}
})
The error I am receiving goes as follows:
(node:17260) UnhandledPromiseRejectionWarning: ReferenceError: client is not defined
at Object.<anonymous> (D:\stuff\S1 Discord Bot\s1-bot\src\events\message\message.js:1:1)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Module.require (internal/modules/cjs/loader.js:952:19)
at require (internal/modules/cjs/helpers.js:88:18)
at registerEvents (D:\stuff\S1 Discord Bot\s1-bot\src\utils\registry.js:33:21)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:17260) 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(). 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:17260) [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.
Thanks
You are missing this from your index file:
const Discord = require("discord.js");
//under const Discord etc
const client = new Discord.Client();
If you are trying to only allow guildMessages, you do it like this:
if (message.channel.type === "dm") return; //dont react to dms
Finally, to send a message to a channel by id:
message.guild.channels.cache.get('814685640088223795').send(msglog); //using 'cache' since v12 uses managers
You seem to be missing two important lines of code:
const Discord = require('discord.js');
const client = new Discord.Client();
Appending these two lines from the discord.js documentation in the beginning of your index.js file should make it work.
The following code sample:
async function expectResolutionErrorCode(object) {
try {
await Promise.resolve(1);
object.f1() // caught error
} catch (error) {
object.f2() // uncaught error
}
}
expectResolutionErrorCode(undefined).catch(err => console.log(err));
Produces the following backtrace when run using node v14:
$ node test.ts
TypeError: Cannot read property 'f2' of undefined
at expectResolutionErrorCode (/Users/bogdan/makabu/unstoppable/resolution/test.ts:6:12)
If I comment out the await statement at line 3 from the sample, the backtrace is complete:
TypeError: Cannot read property 'f2' of undefined
at expectResolutionErrorCode (/Users/bogdan/makabu/unstoppable/resolution/test.ts:6:12)
at Object.<anonymous> (/Users/bogdan/makabu/unstoppable/resolution/test.ts:10:1)
at Module._compile (internal/modules/cjs/loader.js:1201:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1221:10)
at Module.load (internal/modules/cjs/loader.js:1050:32)
at Function.Module._load (internal/modules/cjs/loader.js:938:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47
So the await statement clearly causes node to lose some part of the backtrace.
Why does it behave like that?
Is there any workaround to maintain the backtrace while still using await statements inside try catch?
I tested this behavior in Chrome and Safari and the stacktrace is lost in almost the same way: https://jsfiddle.net/61kdv8fx/
It's because the stack has unwound. Remember that await is syntactic sugar for hooking the settlement of a promise. So when you reach the await in your code, the function returns. Later, when the code continues because the promise was settled, the stack is shallow because promise reactions are called directly.
JavaScript tool makers are very aware of this and working on async call stacks to address it.
However, I should note that when I try to replicate what you're seeing on Node v14, I don't see it, because V8 already has async call stacks. Example:
async function example() {
try {
await Promise.resolve(1); // Could just be `await 1;`, but I wanted to match the question
throw new Error("boom1");
} catch (e) {
throw new Error("boom2");
}
}
async function a() {
await b();
}
async function b() {
await c()
}
async function c() {
await example();
}
a();
When I run it:
$ node example.js
(node:5342) UnhandledPromiseRejectionWarning: Error: boom2
at example (/path/to/example.js:6:15)
at async c (/path/to/example.js:19:5)
at async b (/path/to/example.js:15:5)
at async a (/path/to/example.js:11:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:5342) 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(). 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:5342) [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.
I get the same sort of output on modern versions of Chrome and other browsers using a recent V8. But Firefox v78 still loses the context; I'm sure the SpiderMonkey team are working on it.
My app has to connect to a mysql database but i am stuck just in that moment i cant connect it, im using a method that transforms callbacks code to promise code thats the reason i need to use async and await also the man of the tutorial doesnt have any error i guess because he has diferent terms on the keys.js, he is on linux, root user and also he has a password, things that i dont have. I really need hel thank you.
This is the code that is giving problems:
const express= require('express');
const router= express.Router();
const pool = require('../database');
router.get('/add', (req,res) =>{
res.render('casas/add');
});
router.post('/add', async (req,res) => {
const {titulo, precio, direccion, numhab, superficie} = req.body;
const nuevoPiso={
titulo,
precio,
direccion,
numhab,
superficie
};
await pool.query('INSERT INTO PISOS set ?', [nuevoPiso]);
res.send('recibido');
});
module.exports=router;
The problem is on the await line because if I delete that and the async word it works perfectly but obviously without that I cant send the elements to the database. The error that gives me the terminal is this:
(node:9548) UnhandledPromiseRejectionWarning: Error: ER_ACCESS_DENIED_ERROR: Access denied for user 'Axell'#'localhost' (using password: NO)
at Handshake.Sequence._packetToError (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\protocol\sequences\Sequence.js:47:14)
at Handshake.ErrorPacket (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\protocol\sequences\Handshake.js:123:18)
at Protocol._parsePacket (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\protocol\Protocol.js:291:23)
at Parser._parsePacket (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\protocol\Parser.js:433:10)
at Parser.write (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\protocol\Parser.js:43:10)
at Protocol.write (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\protocol\Protocol.js:38:16)
at Socket.<anonymous> (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\Connection.js:88:28)
at Socket.<anonymous> (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\Connection.js:526:10)
at Socket.emit (events.js:311:20)
at addChunk (_stream_readable.js:294:12)
--------------------
at Protocol._enqueue (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\protocol\Protocol.js:144:48)
at Protocol.handshake (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\protocol\Protocol.js:51:23)
at PoolConnection.connect (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\Connection.js:116:18)
at Pool.getConnection (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\Pool.js:48:16)
at Pool.query (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\Pool.js:202:8)
at internal/util.js:297:30
at new Promise (<anonymous>)
at Pool.query (internal/util.js:296:12)
at C:\Users\Axell\Desktop\node-sql-app\src\routes\casas.js:20:15
at Layer.handle [as handle_request] (C:\Users\Axell\Desktop\node-sql-app\node_modules\express\lib\router\layer.js:95:5)
(node:9548) 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(). 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:9548) [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.
POST /casas/add - - ms - -
(node:9548) UnhandledPromiseRejectionWarning: Error: ER_ACCESS_DENIED_ERROR: Access denied for user 'Axell'#'localhost' (using password: NO)
at Handshake.Sequence._packetToError (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\protocol\sequences\Sequence.js:47:14)
at Handshake.ErrorPacket (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\protocol\sequences\Handshake.js:123:18)
at Protocol._parsePacket (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\protocol\Protocol.js:291:23)
at Parser._parsePacket (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\protocol\Parser.js:433:10)
at Parser.write (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\protocol\Parser.js:43:10)
at Protocol.write (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\protocol\Protocol.js:38:16)
at Socket.<anonymous> (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\Connection.js:88:28)
at Socket.<anonymous> (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\Connection.js:526:10)
at Socket.emit (events.js:311:20)
at addChunk (_stream_readable.js:294:12)
--------------------
at Protocol._enqueue (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\protocol\Protocol.js:144:48)
at Protocol.handshake (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\protocol\Protocol.js:51:23)
at PoolConnection.connect (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\Connection.js:116:18)
at Pool.getConnection (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\Pool.js:48:16)
at Pool.query (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\Pool.js:202:8)
at internal/util.js:297:30
at new Promise (<anonymous>)
at Pool.query (internal/util.js:296:12)
at C:\Users\Axell\Desktop\node-sql-app\src\routes\casas.js:20:15
at Layer.handle [as handle_request] (C:\Users\Axell\Desktop\node-sql-app\node_modules\express\lib\router\layer.js:95:5)
(node:9548) 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(). 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: 2)
POST /casas/add - - ms - -
I dont know where the error is maybe on my keys.js where i have this im on windows that is my username but I dont have a password:
module.exports={
database:{
host:'localhost',
user:'Axell',
database: 'casas',
password: ''
}
};
Here you can download the whole app it is unfinished because I cant continue due to this error: https://mega.nz/#!LAwgwAQK!OiuBqH4qxyT5CW2xRSUXdmhpfRyTtf3TobmYw-NqIic
Thank you so much!
The issue you are having is unrelated to async/await.
The credentials to MySQL incorrect. This could be an incorrect username, an incorrect password or perhaps you did not grant the Axell permission to access the casas database.
Given that you're on localhost, you can test this without localhost. Just try logging on with the same credentials with some other mysql tool (such as the mysql) tool, and you should get a similar error.
I am trying to setup a nodeJS application that .
Using Hapi and PostgreSQL DB.
Referred all documentations but the error persists.
While server.register
server.register({
register: require('hapi-node-postgres'),
options : {
connectionString: "Postgresdb://dbuser:dbpassword#localhost/dbName"
}
}, err => {
console.log(err);
});
The error that is coming is:
UnhandledPromiseRejectionWarning: ***AssertionError [ERR_ASSERTION]: Invalid register options "value" must be an object
at Object.exports.apply*** (/home/sc/code/Reporting(proto)/node_modules/hapi/lib/config.js:22:10)
at internals.Server.register (/home/sc/code/Reporting(proto)/node_modules/hapi/lib/server.js:367:26)
at Object.<anonymous> (/home/sc/code/Reporting(proto)/index.js:16:8)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Function.Module.runMain (module.js:693:10)
at startup (bootstrap_node.js:188:16)
(node:15989) 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:15989) [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.
Please assist.
I am using
"hapi": "^17.5.3"
"hapi-node-postgres": "^4.1.0"
You are using v16 options for registering the plugin as that method is no longer support for the v17 try this link
So, I've been trying to replicate this code:
https://github.com/sindresorhus/np/blob/370ef638344ab7115c956b75dc2823850084da39/index.js#L16
And it works. However, if the promise fails, I get an "unhandled promise" warning. Where does the catch statement belong on something like this if at all? Is there a better way to source information like this?
(node:48454) UnhandledPromiseRejectionWarning: Error: Command failed: np patch --no-cleanup
at makeError (/Users/daghassi/git/build/node_modules/execa/index.js:172:9)
at Promise.all.then.arr (/Users/daghassi/git/build/node_modules/execa/index.js:277:16)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:160:7)
(node:48454) 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: 5)
(node:48454) [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.
(node:48454) UnhandledPromiseRejectionWarning: Error: Command failed: np patch --no-cleanup
at makeError (/Users/daghassi/git/build/node_modules/execa/index.js:172:9)
at Promise.all.then.arr (/Users/daghassi/git/build/node_modules/execa/index.js:277:16)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:160:7)
(node:48454) 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: 6)
(node:48454) UnhandledPromiseRejectionWarning: Error: Command failed: np patch --no-cleanup
Just put a try/catch block around your await call. This should be the same as if you would call a Promise and provide a catch function.
So if you have a function which getPromise() which returns a promise, you simply do this.
async function asyncFunction() {
try {
const result = await getPromise();
} catch (error) {
// Add your error handling code here
}
}