Cannot catch UnhandledPromiseRejectionWarning in promise - javascript

so I'm trying to catch UnhandledPromiseRejectionWarning in my promise, but for some reason it's not working. It ignores my code and just outputs the error to console.
Error:
UnhandledPromiseRejectionWarning: Unhandled promise rejection
(rejection id: 1): Error: Forbidden (Cannot send messages to this
user)
code:
e.message.author.openDM().then((message) => {
message.sendMessage(`test`);
}).catch((error) => {
e.message.channel.sendMessage(error + "test");
});
This is a discord bot, using discordie. In my mind, the above code should send the word "test" to a messages author via private message, if the bot can't, it will send the error and the word test in the channel they sent their message in. However, the second part (inside the catch) doesn't get executed.
tl;dr, The catch in the above code isn't working and I'm getting the above error in console instead if the bot doesn't have permission to dm the user.

You forgot the return statement inside the then function.
I suppose message.sendMessage('test') returns a promise
e.message.author.openDM().then((message) => {
return message.sendMessage(`test`);
}).catch((error) => {
e.message.channel.sendMessage(error + "test");
});

Related

Discord bot returning permission errors

My Discord bot keeps returning these errors and I'm not sure how to deal with them since I'm still very new to this whole coding thing.
UnhandledPromiseRejectionWarning: DiscordAPIError: Missing Permissions
at RequestHandler.execute (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:170:25)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:15) 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: 39)
It seems to happen whenever someone attempts to use a command in a Discord channel where my bot cannot send messages.
This is the code I use for a command:
client.on("message", async message => {
if (message.author.bot || message.content.trim() == "") return;
if (message.content.toLowerCase().trim() == "cat") {
const { file } = await fetch("https://aws.random.cat/meow").then(response =>
response.json()
);
return message.channel.send(new $().setColor("RANDOM").setTitle("Your Cat").setImage(file).setFooter('Powered by Catastic'));
}
});
I hope ya'll can help me!
Your bot doesn't have permissions to send a message to the channel the user have written in. Try giving the "Send Messages" permission in that channel using the Permissions menu.

Why am I getting multiple responses when I'm using async/await?

I'm writing a simple voting web api for a class. I'm currently working on PUT and my code is working, but I'm getting a strange error in my command line terminal. Here is the code I'm using to call PUT:
async addVotes(item) {
try {
let response = await axios.put("/api/candidates/" + item._id);
this.getItems();
return true;
}
catch (error) {
console.log(error);
}
console.log(item.name + " is checked");
},
async submitVotes(items) {
for (var item of this.items) {
if (item.selected) {
this.addVotes(item);
}
else {
console.log(item.name + " is not checked");
}
}
},
and here is the PUT code for the api:
app.put('/api/candidates/:id', async(req, res) => {
console.log("initiated put(edit) request");
try {
let candidate = await Candidate.findOne({ _id: req.params.id });
candidate.numVotes += 1;
candidate.save();
res.send(candidate);
res.sendStatus(200);
}
catch (error) {
console.log(error);
res.sendStatus(500);
}
});
I'm getting an error saying this:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:470:11)
at ServerResponse.header (/var/www/html/MidRev/node_modules/express/lib/response.js:771:10)
at ServerResponse.contentType (/var/www/html/MidRev/node_modules/express/lib/response.js:599:15)
at ServerResponse.sendStatus (/var/www/html/MidRev/node_modules/express/lib/response.js:357:8)
at app.put (/var/www/html/MidRev/start.js:102:9)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:13246) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:470:11)
at ServerResponse.header (/var/www/html/MidRev/node_modules/express/lib/response.js:771:10)
at ServerResponse.contentType (/var/www/html/MidRev/node_modules/express/lib/response.js:599:15)
at ServerResponse.sendStatus (/var/www/html/MidRev/node_modules/express/lib/response.js:357:8)
at app.put (/var/www/html/MidRev/start.js:106:9)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:13246) 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:13246) [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.
From what I've researched online I'm getting this error because I'm getting more than one response, but I am using async/await so I don't understand why I should be getting that error.
The way you add status to the response is incorrect.
Instead of
res.send(candidate);
res.sendStatus(200);
You should do it this way
res.status(200).send(candidate)
sendStatus sends an 'OK' message on top of setting the status code. You may refer to the Express API reference here https://expressjs.com/en/api.html
The problem is with your PUT API implementation in which you're sending the response twice:
res.send(candidate); // sending json response back to client
res.sendStatus(200); // trying to send response status
So if you're sending a json response then you do not need to send response status explicitly.
res.send(candidate); OR res.json(candidate);
However, if you want to specify the response status then you can do chaining like:
res.status(500).send({ error: "boo" });

Twitter Bot Error - Unhandled Promise Rejection?

I wrote this twitter weather bot, which worked fine since last month, but an hour ago it crashed and I can't seem to bring it back up.
Can anyone simply explain me what it is and also what the error is, when it arises and what I have to check to get rid of this warning?
I did search up how to fix an "unhandled promise rejection" but could not find out what it is.
const Twit = require('twit');
const config = require('./config');
const rp = require('request-promise-native');
async function setup(location) {
const options = {
url: "http://api.apixu.com/v1/current.json",
qs: {
key: API_KEY,
q: location
},
json: true
};
let result = await rp(options);
let condition = result.current.condition.text;
let tweetText = `The condition in ${location} is currently ${condition}, and the temperature is ${result.current.temp_c}°C.`;
console.log(tweetText);
sendTweet(tweetText)
}
function sendTweet(text) {
const T = new Twit(config);
var r = Math.floor(Math.random()*1000);
const tweet = {
status: '[' + r + '] ' + text
}
T.post('statuses/update', tweet);
}
setup('Colombo');
2019-08-21T06:41:52.820595+00:00 app[scheduler.8141]: at setup (/app/bot.js:25:36)
2019-08-21T06:41:52.820597+00:00 app[scheduler.8141]: at process._tickCallback (internal/process/next_tick.js:68:7)
2019-08-21T06:41:52.820719+00:00 app[scheduler.8141]: (node:4) 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)
2019-08-21T06:41:52.820834+00:00 app[scheduler.8141]: (node:4) [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.
2019-08-21T06:41:52.903455+00:00 heroku[scheduler.8141]: State changed from up to complete
2019-08-21T06:41:52.880762+00:00 heroku[scheduler.8141]: Process exited with status 0```
When you call the api with:
let result = await rp(options);
You are setting result as a promise to wait for the API call, but your request is not accepted for some reason and then you are getting a promise rejection but not handling.
Please use:
await rp(options).catch(err => console.log(err))
So you can log your error, then we can investigate your error.
---------- EDIT ------------
Just tested it myself, and we are getting a 503 HTTP Status code:
Here is the log print
It means that the service is not available, not receiving requests.
---------- EDIT -----------
It is working again, tried here, I'm getting 200 HTTP Status code and a good response, now you should be good to go

How do I send a custom error message from Node, and display it with catch?

I'm trying to send a custom error message from node, receive it on the frontend, and display it.
On server I'm trying to do:
res.status(500).send('Something broke!')
And on client I'm doing:
try {
const res = await axios.post(`${API_URL}/profiles/signup`, credentials)
} catch(err) {
console.log("Sign up error:", err)
}
What I want is to get something like this in my console:
Sign up error: Something broke!
but I'm getting:
Sign up error: Error: Request failed with status code 500
at createError (createError.js:16)
at settle (settle.js:18)
at XMLHttpRequest.handleLoad (xhr.js:77)
How do I access the custom message I'm sending?
You can create an error with the help of Error()
throw new Error({code: 500, message: 'Sign up error: Something broke!'});
throw send your error to the catch block automatically.
Figured it out:
console.log("Sign up error:", err.response.data)

Getting an array from folder and sending a random file with discord.js

I'm trying to create a command, when requested will send a random image from a folder. I don't want to have to name them cause I have a server with a PHP server where my friends can upload images for the bot to post. This is what I have:
if(command === "meme") {
const path = '/img/memes/';
const fs = require('fs');
fs.readdirSync(path).forEach(file => {
ranfile = Math.floor(Math.random()*file.length);
message.channel.sendFile(ranfile);
})
return;
}
When I run the bot with Node.js I get this error:
(node:4840) 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)
Anyone know what the issue is?
This is probably just a regular error wrapped in an UnhandledPromiseRejectionWarning. Have you tried running with --trace-warnings?
This should solve the problem of getting to the actual issue by providing a reasonable stack trace.

Categories

Resources