Event emitter - UnhandledPromiseRejectionWarning: Unhandled promise rejection - javascript

I'm firing an event to send an email from my controller but when nodemailer fails to send the email for good reasons like password and username being wrong, i get a unhandled promise rejection error in stack trace. I also emit an error when node mailer fails to send the email,listen to it and then throw another error but it isn't reaching the controller level to be handled by the try catch.
this is the method in the controller where i fire the event
sendMail = async(emitterPayload: any): Promise<any> => {
try {=
//other asynchronous operations
EventEmitter.emit('SEND MAIL', emitterPayload);
} catch (err) {
throw new Error(err);
}
};
How i listen to 'SEND MAIL' event. When no error , the email is sent successfully
EventEmitter.on(
'SEND MAIL',
(emitterPayload) => {
NodeMailerService.sendEmail(emitterPayload).catch(function(error) {
//fire this event when error occurs
EventEmitters.emit('error',new Error(error));
});
},
);
When an 'error' is fired, i listen to it like this
EventEmitter.on(
'error',
err => {
throw new Error(err);
},
);
But i instead get Unhandled promise rejection. How can i throw an error as shown above and have my controller handle it. What i'm i missing or doing wrong?
the complete 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(). 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:12960) [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

Related

Getting a discord bot to set the role of a guild member from DM's

So i am trying to make my discord bot add roles to someone that dm-ed it, and i cant seem to make it work
Here is the code:
guild.members.fetch(message.author)
.then(member => {
member.roles.set(['roleID']);
});
This is the error that i get:
(node:5692) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'set' of undefined
at D:\Documents\GitHub\InfinitBotPrototip\index.js:48:24
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:5692) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise w
hich 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_unhand
led_rejections_mode). (rejection id: 1)
(node:5692) [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 e
xit code.

UnhandledPromiseRejectionWarning even though using .catch() (Node.js)

I'm using Node.js and Express to build a REST api. The database operations are in a separate file called "db.js". Here's the gist of the code:
...
const db = require('./db');
app.get('/b50api/workitems/me/:pernr', function (req, rs) {
db.getWorkItems("200805").then((items, output)=>{
console.log("ITEMS:", items);
console.log("OUTPUT:", output);
}).catch(err => {
console.log("ERROR:", err);
})
})
...
When I hit this endpoint the program fails with the error below.
I created a test .js file (below) and this runs just fine:
const db = require('./db');
function test() {
db.getWorkItems("200805").then((items, output)=>{
console.log("ITEMS:", items);
console.log("OUTPUT:", output);
}).catch(err => {
console.log("ERROR:", err);
})
}
test();
What am I missing??
Here's the error information when running in my REST api:
(node:14612) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.
(node:14612) UnhandledPromiseRejectionWarning: TypeError: p.callNotify is not a function
at C:\inetpub\wwwroot\PersonnelApps\b50api\node_modules\msnodesqlv8\lib\procedure.js:332:11
at C:\inetpub\wwwroot\PersonnelApps\b50api\node_modules\msnodesqlv8\lib\procedure.js:305:13
at C:\inetpub\wwwroot\PersonnelApps\b50api\node_modules\msnodesqlv8\lib\procedure.js:194:9
at runNextTicks (internal/process/task_queues.js:62:5)
at processImmediate (internal/timers.js:429:9)
(node:14612) 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:14612) [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.
Turns out the issue was it was attempting to connect to the database as some built-in account. I need to change the site to an application and change the account it's running under to the one that needs to authenticate to the SQL Server (along with making that same account one that can log on as a service).

UnhandledPromiseRejectionWarning: Error: Script failed to execute- Electron execute script

i try to excuteJavaScript in electron
function createTestGmail(username, password){
username = '12344444444444444444444444asdasd44444444'
testGmail = new BrowserWindow({
width: 500,
height:300,
backgroundColor:'#ccc',
title:'Kiểm tra Gmail',
webPreferences: {
nodeIntegration: true,
nativeWindowOpen: true,
}
});
testGmail.loadURL('https://example.com');
testGmail.webContents.openDevTools();
testGmail.webContents.executeJavaScript(`
console.log(`+username+`)
`)
testGmail.on('closed',()=>{
testGmail = null;
})
}
if username is a number it work correctly, if username is a string, like below, it show error code
(node:3752) UnhandledPromiseRejectionWarning: Error: Script failed to execute, this normally means an error was thrown. Check the renderer console for the error.
at WebFrame.<computed> (C:\Users\Vy\Desktop\toolyoutube\node_modules\electron\dist\resources\electron.asar\renderer\api\web-frame.js:64:33)
at WebFrame.executeJavaScript (C:\Users\Vy\Desktop\toolyoutube\node_modules\electron\dist\resources\electron.asar\common\api\deprecate.js:114:32)
at C:\Users\Vy\Desktop\toolyoutube\node_modules\electron\dist\resources\electron.asar\renderer\web-frame-init.js:11:43
at C:\Users\Vy\Desktop\toolyoutube\node_modules\electron\dist\resources\electron.asar\renderer\ipc-renderer-internal-utils.js:7:40
at new Promise (<anonymous>)
at EventEmitter.<anonymous> (C:\Users\Vy\Desktop\toolyoutube\node_modules\electron\dist\resources\electron.asar\renderer\ipc-renderer-internal-utils.js:7:9)
at EventEmitter.emit (events.js:200:13)
at Object.onMessage (C:\Users\Vy\Desktop\toolyoutube\node_modules\electron\dist\resources\electron.asar\renderer\init.js:42:16)
(node:3752) 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:3752) 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:3752) [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:3752) [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 have try with tag and it have the same problem
I saw #Bravo answered your question through a comment, but just to improve it, since you're using a template string, you could just:
testGmail.webContents.executeJavaScript(`console.log('${username}')`)
It's cleaner that way (since this is the main purpose of a template string, not only allowing to have a multiline text) and you avoid doing string concatenation with the "+" operator.
Sometimes you will mess with single quote and quote mark.
I made an util function to log everywhere.
function logEverywhere(mainWindow, message) {
if (mainWindow && mainWindow.webContents) {
mainWindow.webContents.executeJavaScript(`console.log(\`${message}\`)`);
}
}
I was taking a UDEMY course called Master Electron: Desktop Apps with HTML, JavaScript & CSS, by Ray Viljoen
And in Lesson 3.17. Session: DownloadItem, I got this same error:
(node:9552) UnhandledPromiseRejectionWarning: Error: Script failed to execute, this normally means an error was thrown. Check the renderer console for the error.
at WebFrame.e.startsWith.e.startsWith.WebFrame.<computed> [as _executeJavaScript] (electron/js2c/renderer_init.js:87:1542)
at electron/js2c/renderer_init.js:139:429
at electron/js2c/renderer_init.js:123:361
at EventEmitter.<anonymous> (electron/js2c/renderer_init.js:127:872)
at EventEmitter.emit (events.js:223:5)
at Object.onMessage (electron/js2c/renderer_init.js:115:818)
(node:9552) 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:9552) [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.
In my case I tracked the bug/problem down to some code that had a divide by zero in the event handler for DownloadItem.on. The code snippet in question is:
ses.on('will-download', (e, downloadItem, webContents) => {
let fileName = downloadItem.getFilename()
let fileSize = downloadItem.getTotalBytes() // this was zero (which caused the bug)
downloadItem.on('updated', (e, state) => {
let received = downloadItem.getReceivedBytes()
if (state === 'progressing' && received) {
// THE NEXT LINE CAUSED the divide by zero exception because fileSize was zero.
let progress = Math.round((received/fileSize)*100)
webContents.executeJavaScript(`window.progress.value = ${progress}`)
}
})
})
So my takeaway is that Electron's stack didn't help me identify where the bug is but the but was a normal coding error. Not having an exception that included a line number of my code made this particularly difficult to debug/isolate.
The underlying problem was caused by the URL being used when the course was written no longer working. From site: https://file-examples.com/.

Error with discord bot on sending message

I'm getting this strange error on adding this sending message with the discord Bot. I was following the Scratch Tutorial & everything went fine except this when I try to send a message on bot active.
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
client.user.setActivity('You', {type: 'WATCHING'});
var mainChannel = client.channels.get('51549559XXXX')
mainChannel.send("Hello, world!")
});
client.on('message', (received) => {
if (received.author == client.user) {
return
}
received.channel.send("You: " + received.content);
});
client.login('TOKEN');
Result:-
`(node:8480) UnhandledPromiseRejectionWarning: DiscordAPIError: Missing Access
at C:\Users\Deepanshu\node_modules\discord.js\src\client\rest\RequestHandlers\Sequential.js:85:15
at C:\Users\Deepanshu\node_modules\snekfetch\src\index.js:215:21
at processTicksAndRejections (internal/process/task_queues.js:85:5)
(node:8480) 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: 2)
(node:8480) [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:8480) UnhandledPromiseRejectionWarning: DiscordAPIError: Missing Permissions
at C:\Users\Deepanshu\node_modules\discord.js\src\client\rest\RequestHandlers\Sequential.js:85:15
at C:\Users\Deepanshu\node_modules\snekfetch\src\index.js:215:21
at processTicksAndRejections (internal/process/task_queues.js:85:5)
(node:8480) 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: 4)
I have copied your code and tried it, and it works perfectly fine. So the problem must be with some of your permissions, as shown by the error. Maybe the mainChannel that you're trying to send a message doesn't allow messages to be sent from the bot.

Unhandled promise rejection when making connection to MongoDB

Hello there is my code below I have a problem since this afternoon I have two errors in the console:
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: 2)
(node:90699) [DEP0018]
DeprecationWarning: Unhandled promiserejections are deprecated. In the future, promise rejectionsthat are not handled will terminate the Node.js process witha non-zero exit code.
I switched to mongo client upstairs I think it's fine though the promised line 11 I think it's not fine
import {MongoClient} from 'mongodb'
MongoClient.connect('mongodb://localhost:27017/chatapp',
{userNewUrlParser:true});
export default class Database{
connect(){
return new Promise((resolve, reject) => {
MongoClient.connect(URL, (err, db) => {
return err ? reject(err) : resolve(db);
});
});
}
}
What's wrong? What's missing?

Categories

Resources