Getting error UnhandledPromiseRejectionWarning - node.js

Trying to run a sftp client using nodejs but getting a wired error. The error is
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)
let Client = require('ssh2-sftp-client');
let sftp = new Client();
const process = require('process');
const config = {
host: 'localhost',
port: '1026',
username: 'Nav****',
password: '*******'
}
sftp.connect(config)
const list = ()=>{
sftp.connect(config).then(() => {
return sftp.list('../send_backend');
}).then((data) => {
console.log(data, 'the data info');
}).catch((err) => {
console.log(err, 'catch error');
})
}
console.log("=======================================");
console.log("received data =>" + list());

What is "sftp.connect(config)" doing outside the list. As I can see you are neither using resolve nor the rejected case. That is causing the issue. So you should either handle the exception or remove that code!
In case you want to handle it
sftp.connect(config)
.then(()=>{//do something here})
.catch((exception)=>{ console.log(exception) // do something else })
As discussed in comments, You may use this:
let Client = require('ssh2-sftp-client');
let sftp = new Client();
const process = require('process');
const config = {
host: 'localhost',
port: '1026',
username: 'Nav****',
password: '*******'
}
sftp.connect(config)
.then(()=>{
// what you want to do after you make connection goes here
})
.catch((exception)=>{
console.log(exception) // do something else
})

Related

Expected 'port' to be a 'number', got 'object', minecraft server status check error

i have this simple code in my discord bot to check mc server.
const Discord = require('discord.js')
const client = new Discord.Client()
const { MessageButton, MessageButtonStyles } = require('discord-buttons')
require('discord-buttons')(client)
const db = require('quick.db')
let mineutil = require('minecraft-server-util')
client.on('ready', () => {
console.log('Started!\n---')
client.user.setPresence({
status: 'online',
activity: {
type: 'LISTENING',
name: '!help'
}
})
})
client.on('message', async (message) => {
if (message.content == 'привет') {
message.reply('привет')
}
//more code
const SERVER_ADDRESS = 'adress'
const SERVER_PORT = 25565
const STATUS_ONLINE = '**Сервер включен** - '
const STATUS_PLAYERS = '**{online}** **человек(a) онлайн!**'
const STATUS_EMPTY = '**никто не играет**'
const cacheTime = 15 * 1000; // 15 sec cache time
let data, lastUpdated = 0;
function statusCommand(message) {
getStatus().then(data => {
let status = STATUS_ONLINE;
status += data.onlinePlayers ?
STATUS_PLAYERS.replace('{online}', data.onlinePlayers) : STATUS_EMPTY;
let statuspanel = new Discord.MessageEmbed()
.setColor('2ecc71')
.setDescription(status)
send(statuspanel)
}).catch(err => {
console.error(err)
let statuserror = new Discord.MessageEmbed()
.setColor('ff0000')
.setDescription('**Сервер выключен**')
send(statuserror)
})
}
function getStatus() {
if (Date.now() < lastUpdated + cacheTime) return Promise.resolve(data);
return mineutil.status(SERVER_ADDRESS, { port: SERVER_PORT })
.then(res => {
data = res;
lastUpdated = Date.now();
return data;
})
}
if (message.content == '!server') {
statusCommand(message)
}
})
client.login(TOKEN)
And it works in Visual studio, but i just placed it on Replit and it catches this error:
(node:172) UnhandledPromiseRejectionWarning: AssertionError [ERR_ASSERTION]: Expected 'port' to be a 'number', got 'object'
at Object.status (/home/runner/Makak-discord-bot/node_modules/minecraft-server-util/dist/status.js:23:26)
at getStatus (/home/runner/Makak-discord-bot/index.js:210:21)
at statusCommand (/home/runner/Makak-discord-bot/index.js:192:5)
at Client.<anonymous> (/home/runner/Makak-discord-bot/index.js:219:5)
at Client.emit (events.js:314:20)
at Client.EventEmitter.emit (domain.js:483:12)
at MessageCreateAction.handle (/home/runner/Makak-discord-bot/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (/home/runner/Makak-discord-bot/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (/home/runner/Makak-discord-bot/node_modules/discord.js/src/client/websocket/WebSocketManager.js:384:31)
at WebSocketShard.onPacket (/home/runner/Makak-discord-bot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
(node:172) 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:172) [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.
And if i change, for example { port: SERVER_PORT } to 25565, it always says that server is off, even if server online(
PS sorry for my english, and russian text in code
EDIT Just saw the question's last line about the server being reported as offline when using a number rather than an object. That actually confirms my suspicion below, as you're no longer getting an error from the SDK itself (ie, it seems to be "working," in that it's at least making the network call). I would double-check your address and port number, and ensure the server is accessible from replit.
--- Original response below ---
Difficult to say for sure without knowing the mineutil API you're using, but it looks like you may be sending more than you need to the mineutil.status() function (And if you're using this library, I'm fairly certain you are).
I'm guessing that the following line:
return mineutil.status(SERVER_ADDRESS, { port: SERVER_PORT })
which is sending an object `{port: SERVER_PORT}' as its second parameter, should just be sending the number itself. For example:
return mineutil.status(SERVER_ADDRESS, SERVER_PORT )
This is Replit server side error, it can not be repaired(

Nodejs Netsuite restless Error : (node:1128) UnhandledPromiseRejectionWarning: Unhandled promise rejection

I am using nodejs npm module netsuite-rest to connect to netsuite rest web services and I am getting this error : UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch bloc
let NetSuiteRestlet = require('netsuite-restlet');
const config = {
account: 'XXXXX',
username: 'XXXXX',
password: 'XXXX',
role: 'FOM PH Sales Manager'
};
const url = 'https://6218235.suitetalk.api.netsuite.com';
const parameters = {
internalid: 1054
};
let ns = new NetSuiteRestlet(config);
// Example using the get function
ns.get(parameters, url).then((out) => { console.log(out) });
It looks like your get request is failing, but is not being handled correctly.
Since you are using promises, you would simply chain on a .catch after the .then to catch the promise rejection.
For example:
ns.get(parameters, URL)
.then((out) => { console.log(out) })
.catch((error) => {
console.log(error) // and/or handle the error some other way
}
See here for more:
How to handle promise rejections: https://flaviocopes.com/javascript-promises-rejection/

(node:23977) UnhandledPromiseRejectionWarning: Error: Missing credentials for "PLAIN"

I'm trying to send emails from the site to the post office Mail.ru, but the following error appears:
(node:25258) UnhandledPromiseRejectionWarning: Error: Missing credentials for "PLAIN"
at SMTPConnection._formatError (/home/user/server/node_modules/nodemailer/lib/smtp-connection/index.js:784:19)
at SMTPConnection.login (/home/user/server/node_modules/nodemailer/lib/smtp-connection/index.js:448:38)
at /home/user/server/node_modules/nodemailer/lib/smtp-transport/index.js:271:32
at SMTPConnection.<anonymous> (/home/user/server/node_modules/nodemailer/lib/smtp-connection/index.js:215:17)
at Object.onceWrapper (events.js:421:28)
at SMTPConnection.emit (events.js:315:20)
at SMTPConnection._actionEHLO (/home/user/server/node_modules/nodemailer/lib/smtp-connection/index.js:1313:14)
at SMTPConnection._processResponse (/home/user/server/node_modules/nodemailer/lib/smtp-connection/index.js:942:20)
at SMTPConnection._onData (/home/user/server/node_modules/nodemailer/lib/smtp-connection/index.js:749:14)
at TLSSocket.SMTPConnection._onSocketData (/home/user/server/node_modules/nodemailer/lib/smtp-connection/index.js:195:44)
(node:25258) 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:25258) [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.
And here is the backend code itself:
const express = require('express');
const nodemailer = require('nodemailer');
const Parser = require('body-parser');
const sqlite3 = require('sqlite3').verbose();
const server = express();
let path_services = ( __dirname + '/public/static/img/services/' );
let path_html = ( __dirname + '/public/index.html' );
let path_font = ( __dirname + '/public/static/font/' );
let path_css = ( __dirname + '/public/static/css/' );
let path_img = ( __dirname + '/public/static/img/' );
let path_js = ( __dirname + '/public/static/js/' );
let path_db = ( __dirname + '/Main.db' );
const Body_Parser = Parser.urlencoded({extended: false});
server.get('/', Body_Parser , function(request, response) {
response.sendFile(path_html);
});
server.post('/', Body_Parser, function(request, response) {
let db = new sqlite3.Database(path_db, sqlite3.OPEN_READWRITE, (err) => {
if(err) {
console.error(err.message);
}
console.log('Connected to Database!');
});
db.run('INSERT INTO Client(firstname, lastname, email, phone, message) VALUES($firstname, $lastname, $email, $phone, $message)', {
$firstname: request.body.ghostName,
$lastname: request.body.ghostSurname,
$email: request.body.ghostEmail,
$phone: request.body.ghostPhone,
$message: request.body.ghostMessage
}, function(err) {
if(err) {
console.log(err.message);
}
console.log('Good!');
response.end('Ok!');
});
db.close();
let testEmailAccount = nodemailer.createTestAccount();
let transporter = nodemailer.createTransport({
service: 'email',
host: 'smtp.ethereal.email',
port: 587,
secure: false,
auth: {
type: "login", // default
user: testEmailAccount.user,
pass: testEmailAccount.pass
}
});
let result = transporter.sendMail({
from: '"Node js" <nodejs#example.com>',
to: "chrome_777111777#mail.ru",
subject: "Message from Node js",
text: "This message was sent from Node js server.",
html: "This <i>message</i> was sent from <strong>Node js</strong> server."
});
console.log(result);
});
server.use(express.static (path_services) );
server.use(express.static (path_font) );
server.use(express.static (path_css) );
server.use(express.static (path_img) );
server.use(express.static (path_js) );
server.listen(8000);
I am asking you for help, because I have already visited a huge number of sites (starting with the official documentation and ending with a lot of unfamiliar forums), but everywhere I went it was said about sending emails to Gmail, about sending emails to email was said only in the documentation and on several other sites that copied information from the documentation. I will be very grateful to you if you help!
nodemailer.createTestAccount is an async function, that means, you just have to put the await keyword in front of it like that:
let testEmailAccount = await nodemailer.createTestAccount();
Otherwise testEmailAccount is a promise and testEmailAccount.user and testEmailAccount result as undefined.
In your case you also have to make your app.post callback an async function:
server.post('/', Body_Parser, async function(request, response) {
// ...
}

Keep getting the "ConfigError: Missing region in config" error in Node.js no matter what I do

I keep getting the "UnhandledPromiseRejectionWarning: ConfigError: Missing region in config" when trying to make requests to APIs I have set up in Node.js.
I'm new to DynamoDB and after setting up most of my boilerplate code I'm using Postman to test my routes. However I keep getting the same error each time I make a post request. I've checked some solutions on existing threads, namely: Configuring region in Node.js AWS SDK but cannot get it to work.
I am currently developing the app locally and checked the database where the items are being added.
My setup is as follows:
// user_controller.js
const uuid = require('uuid');
const sanitizer = require('validator');
const bcrypt = require('bcryptjs-then');
const AWS = require('aws-sdk');
const config = require('../config/config');
const { signToken, userByEmail, userById } = require('../Helpers/Users');
const isDev = true
Then in my code block I have the following:
// user_controller.js
(...)
if (isDev) {
AWS.config.update(config.aws_local_config);
} else {
AWS.config.update(config.aws_remote_config);
}
const DB = new AWS.DynamoDB.DocumentClient();
const params = {
TableName: config.aws_table_name,
Item: {
userId: await uuid.v1(),
firstName: sanitizer.trim(firstName),
lastName: sanitizer.trim(lastName),
email: sanitizer.normalizeEmail(sanitizer.trim(email)),
password: await bcrypt.hash(password, 8),
level: 'standard',
createdAt: new Date().getTime(),
updatedAt: new Date().getTime(),
},
}
return userByEmail(params.Item.email) // Does the email already exist?
.then(user => { if (user) throw new Error('User with that email exists') })
.then(() => DB.put(params).promise()) // Add the data to the DB
.then(() => userById(params.Item.id)) // Get user data from DB
.then(user => (err, data) => {
console.log("AFTER USER CREATED")
if (err) {
res.send({
success: false,
message: 'Error: Server error'
});
} else {
console.log('data', data);
res.send({
statusCode: 201,
message: 'Success - you are now registered',
data: { token: signToken(params.Item.id), ...user },
});
}
})
(...)
Finally I am importing the config from separate file:
// config.js
module.exports = {
aws_table_name: 'usersTable',
aws_local_config: {
region: 'local',
endpoint: 'http://localhost:8000'
},
aws_remote_config: {}
}
In have already configured the aws-sdk:
AWS Access Key ID [****************foo]:
AWS Secret Access Key [****************bar]:
Default region name [local]:
Default output format [json]:
Here is the output I keep getting:
(node:4568) UnhandledPromiseRejectionWarning: ConfigError: Missing region in config
at Request.VALIDATE_REGION (/Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/event_listeners.js:92:45)
at Request.callListeners (/Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/sequential_executor.js:106:20)
at callNextListener (/Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/sequential_executor.js:96:12)
at /Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/event_listeners.js:86:9
at finish (/Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/config.js:350:7)
at /Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/config.js:368:9
at SharedIniFileCredentials.get (/Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/credentials.js:127:7)
at getAsyncCredentials (/Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/config.js:362:24)
at Config.getCredentials (/Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/config.js:382:9)
at Request.VALIDATE_CREDENTIALS (/Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/event_listeners.js:81:26)
(node:4568) 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)
(node:4568) [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.
Like I said, I've tried a lot of variations on this but to no avail. Would love some help, thanks.
I dont know if this helps, but I used none instead of local for the region and it seemed to work for me
AWS.config.update({ region: 'none' })

UnhandledPromiseRejectionWarning: Error: Network error: apollo_cache_inmemory_1.readQueryFromStore is not a function aws appsync nodejs

I am trying to call an Graphql Query for my AWS AppSync app through nodejs. The error I am encountering is
UnhandledPromiseRejectionWarning: Error: Network error:
apollo_cache_inmemory_1.readQueryFromStore
This is my index.js code
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var config = {
AWS_ACCESS_KEY_ID: <ACCESS_KEY_ID>,
AWS_SECRET_ACCESS_KEY: <SECRET_KEY>,
HOST: '<HOST_URL>',
REGION: 'us-west-2',
PATH: '/graphql',
ENDPOINT: '<AWS_APPSYNC_ENDPOINT>',
};
config.ENDPOINT = "https://" + config.HOST + config.PATH;
exports.default = config;
global.localStorage = {
store: {},
getItem: function (key) {
return this.store[key]
},
setItem: function (key, value) {
this.store[key] = value
},
removeItem: function (key) {
delete this.store[key]
}
};
require('es6-promise').polyfill();
require('isomorphic-fetch');
// Require AppSync module
const AUTH_TYPE = "AWS_IAM";
const AWSAppSyncClient = require('aws-appsync').default;
const url = config.ENDPOINT;
const region = config.REGION;
const type = AUTH_TYPE.AWS_IAM;
// If you want to use API key-based auth
const apiKey = 'xxxxxxxxx';
// If you want to use a jwtToken from Amazon Cognito identity:
const jwtToken = 'xxxxxxxx';
// If you want to use AWS...
const AWS = require('aws-sdk');
AWS.config.update({
region: config.REGION,
credentials: new AWS.Credentials({
accessKeyId: config.AWS_ACCESS_KEY_ID,
secretAccessKey: config.AWS_SECRET_ACCESS_KEY
})
});
const credentials = AWS.config.credentials;
// Import gql helper and craft a GraphQL query
const gql = require('graphql-tag');
const query = gql(`
query {
getSample {
mobileNumber
}
}
`);
// Set up Apollo client
const client = new AWSAppSyncClient({
url: url,
region: region,
auth: {
type: type,
credentials: credentials,
}
});
client.hydrated().then(function a(client) {
client.query({query: query});
client.query({ query: query, fetchPolicy: 'network-only'}).then(function(data) {
console.log("data: " + queryResult);
})
});
The complete stacktrace is the following:
UnhandledPromiseRejectionWarning: Error: Network error:
apollo_cache_inmemory_1.readQueryFromStore is not a function
at new ApolloError (/Users/kanhaiagarwal/appsync1/node_modules/aws-appsync/node_modules/apollo-client/bundle.umd.js:124:32)
at /Users/kanhaiagarwal/appsync1/node_modules/aws-appsync/node_modules/apollo-client/bundle.umd.js:1248:45
at /Users/kanhaiagarwal/appsync1/node_modules/aws-appsync/node_modules/apollo-client/bundle.umd.js:1680:21
at Array.forEach ()
at /Users/kanhaiagarwal/appsync1/node_modules/aws-appsync/node_modules/apollo-client/bundle.umd.js:1679:22
at Map.forEach ()
at QueryManager.broadcastQueries (/Users/kanhaiagarwal/appsync1/node_modules/aws-appsync/node_modules/apollo-client/bundle.umd.js:1672:26)
at /Users/kanhaiagarwal/appsync1/node_modules/aws-appsync/node_modules/apollo-client/bundle.umd.js:1175:35
at (node:23377) 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:23377) [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.
Can someone suggest a solution for this?
The problem is caused by not providing a window object that the aws-appsync package relies on for some global objects. This is not present in the Node.js environment and adding the following at the start of your script should make it work:
global.window = global.window || {
setTimeout: setTimeout,
clearTimeout: clearTimeout,
WebSocket: global.WebSocket,
ArrayBuffer: global.ArrayBuffer,
addEventListener: function () { },
navigator: { onLine: true }
};
Here's the GitHub issue where the answer was proposed:
https://github.com/awslabs/aws-mobile-appsync-sdk-js/issues/276#issuecomment-432983691

Resources