ERR_UNHANDLED_REJECTION - axios

node:internal/process/promises:279
triggerUncaughtException(err, true /* fromPromise */);
^
[UnhandledPromiseRejection: 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(). The promise rejected with the reason "AxiosError: Request failed with status code 403".] {
code: 'ERR_UNHANDLED_REJECTION'
}

Related

How to deal with HTTP connection timed out crashes in Flutter

So I have a method that uses the Flutter HTTP library and is responsible for calling HTTP requests to the server with code like this:
Future<List<DataModel>> fetchData() async {
try {
var url = Uri.parse('${baseUrlParse}myapipath');
var request = await http.get(url);
var data = jsonDecode(request.body);
return data;
} catch (e) {
print('Catch ${e}');
rethrow;
}
}
This code runs fine and has no issues.
It got to the point where when I have no internet connection or server connection fails, the app freezes, and an error file appears (if you're debugging in VS Code), called http_impl.dart, and the error snippet goes something like this:
onError: (error) {
// When there is a timeout, there is a race in which the connectionTask
// Future won't be completed with an error before the socketFuture here
// is completed with a TimeoutException by the onTimeout callback above.
// In this case, propagate a SocketException as specified by the
// HttpClient.connectionTimeout docs.
if (error is TimeoutException) {
assert(connectionTimeout != null);
_connecting--;
_socketTasks.remove(task);
task.cancel();
throw SocketException(
"HTTP connection timed out after $connectionTimeout, "
"host: $host, port: $port");
}
_socketTasks.remove(task);
_checkPending();
throw error;
});
I have tried to implement from this source and this, but when I make a request but have no connection, this error still occurs.
How to deal with this problem?
What I want is, if there is a problem with HTTP either there is no connection, or it fails to contact the server, then I can make a notification..
Is there something wrong with my code?
Please help, thank you
You re throw the exception in your code,
You need to catch exception where you call to this method like this.
try {
await fetchData();
} catch (e) {
// TODO: handle exception
}
You can stop VS Code catching unhandled exceptions from this way
https://superuser.com/a/1609472

(node:2072) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'send' of undefined Discord js | Mongoose | MongoDB

I am trying to make a simple welcome message on discord js with an event handler. It would work if I do it on the main file, but it does not work when I try it here. Code Below:
const profileModel = require('../../database/models/profileSchema');
let WelcomeSchema = require(`../../database/models/welcomeSchema`)
const Discord = require(`discord.js`)
const mongoose = require(`mongoose`)
module.exports = (client, member, GuildMember) => {
WelcomeSchema.findOne({ guildID: member.guild.id}, async (err, data, user) => {
console.log(member.guild.id)
if(!data) return;
const channel = await client.channels.cache.find(x => x.id === `${data.WelcomeChannel}`)
channel.send(`Welcome ${member}, ${data.WelcomeMsg}`)
})
}
Below Is My Event Handler (keep in mind the code above had the file name of, guildMemberAdd)
fs.readdirSync(`./events`).forEach(dirs => {
const events = fs.readdirSync(`./events/${dirs}`).filter(file => file.endsWith(`.js`))
for (const file of events) {
console.log(`Loading discord.js event ${file}`);
const event = require(`./events/${dirs}/${file}`);
client.on(file.split(".")[0], event.bind(null, client));
}
});
Below Is The Full Error
(node:2072) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'send' of undefined
at E:\Software\Github Repository shit\EA-BOT\events\Other\guildMemberAdd.js:15:13
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(node:2072) 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:2072) [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.
Below Is Line 15 (where the error was at)
(line 14) const channel = await client.channels.cache.find(x => x.id === `${data.WelcomeChannel}`)
(line 15) channel.send(`Welcome ${member}, ${data.WelcomeMsg}`)
The error is self-explanatory. Cannot read property 'send' of undefined you are attempting to invoke .send() method of something undefined - meaning channel is undefined. If we take a look at line 14, the logical explanation is that there is no channel, for which
x.id === `${data.WelcomeChannel}`
is true.
The line if (!data) return; for your purposes is not specific enough. It appears data exists, but either data.WelcomeChannel does not, or IDs don't much.
Try to use line if (!data.WelcomeChannel) return; and see if this exits your code. Then double-check data.WelcomeChannel is a correct channel id (and if it's actually an id, not channel object).
Instead of using this:
const channel = await client.channels.cache.find(x => x.id === `${data.WelcomeChannel}`)
to get your Discord.channel, try doing this:
const channel = await client.channels.cache.get(data.WelcomeChannel)
Note: I can't test the fix myself because I'm currently in school, but this may fix your issue.

Receive commands from a specific channel

How can I make the bot receive commands from specific channels, and if there is no channel, it is received from all channels and it is connected to mongoDB?
I can do the receiving command from a specific channel using channel ID, but I want via the command:
!setChannel #ID_CHANNEL OR mention
I tried these codes
let channel = message.mentions.channels.first()
if(!args[0]) return message.channel.send('Please Mention Channel');
if(!channel) return message.channel.send('Please Mention Vaild Channel');
/*-----------------------------in mongedb add Guild id + channel id------------------------------
in quick.db it is like this -->
db.set("commands_channel_"+ message.guild.id + channel.id, true)*/
message.channel.send(`Commands Channel: ${channel}`);
let CommandsChannel = db.get("commands_channel_"+ message.guild.id + channel.id)
if(!CommandsChannel) return
//-------------------------------//
if(CommandsChannel = true) {
// else command code //
}
wrong with the code
(node:4456) UnhandledPromiseRejectionWarning: Error: `commands_channel_708596988995829762709436321805893753` is an invalid option.
at Mongoose.set (/rbd/pnpm-volume/34e95e32-ea3c-4e44-8fb4-6f803dcbc088/node_modules/.registry.npmjs.org/mongoose/5.10.15/node_modules/mongoose/lib/index.js:179:48)
at Object.run (/app/commands/admin/setchannel.js:19:10)
at module.exports (/app/events/message.js:152:17)
at processTicksAndRejections (internal/process/task_queues.js:88:5)
(node:4456) 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)

Protractor isDisplayed has no .catch, leading to UnhandledPromiseRejectionWarning

Then "Thenable" returned by ElementFinder.isDisplayed has no catch.
let promise = element(by.css('donut')).isDisplayed();
console.log(promise.then); // => (fn, errorFn) => ...
console.log(promise.catch); // => undefined
If I use try-catch in an async function:
try {
await e.isDisplayed();
} catch (e) {
console.log(e);
}
I do catch the exception, but then I get an UnhandledPromiseRejectionWarning from Node, with a deprecation warning:
(node:12296) UnhandledPromiseRejectionWarning: NoSuchElementError: No element found using locator: By(css selector, donut)
...
(node:12296) [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.
How can handle that promise rejection? I can't use .catch on the value returned by isDisplayed, and apparently using a try-catch in an async function isn't enough.
NOTE: I'm aware that I can use e.isPresent() to find out in advance if e.isDisplayed() will throw, but the question is not how to avoid this error, but why it cannot be caught.

Vertx - using the Router failureHandler for the errors in async calls

We have recently discovered the failureHandler in the Vertx router
We thought it could help us get rid of all the repetitive try-catch blocks we have. But alas, it seems that the exceptions that are thrown inside the callbacks are not caught by the failureHandler.
Example: below, the failureHandler is called only for the 3rd case:
// Get the user details
router.get("/user").handler(ctx -> {
ctx.response().headers().add("content-type", "application/json");
// some async operation
userApiImpl.getUser(ctx, httpClient, asyncResult -> {
// ctx.response().setStatusCode(404).end(); //1
// throw new RuntimeException("sth happened"); //2
ctx.fail(404); //3
});
});
// ============================
// ERROR HANDLER
// ============================
router.get("/user").failureHandler(ctx -> {
LOG.info("Error handler is in the action.");
ctx.response().setStatusCode(ctx.statusCode()).end("Error occurred in method");
});
Is this as expected?
Can we somehow declare a global try-catch in a router for the exceptions occurring in the async context?
It is expected that sending a response manually with an error code does not trigger the failure handler.
It should be triggered if:
the route path matches
a handler throws an exception or ctx.fail() is invoked
Here's an example:
Route route1 = router.get("/somepath/path1/");
route1.handler(routingContext -> {
// Let's say this throws a RuntimeException
throw new RuntimeException("something happened!");
});
Route route2 = router.get("/somepath/path2");
route2.handler(routingContext -> {
// This one deliberately fails the request passing in the status code
// E.g. 403 - Forbidden
routingContext.fail(403);
});
// Define a failure handler
// This will get called for any failures in the above handlers
Route route3 = router.get("/somepath/*");
route3.failureHandler(failureRoutingContext -> {
int statusCode = failureRoutingContext.statusCode();
// Status code will be 500 for the RuntimeException or 403 for the other failure
HttpServerResponse response = failureRoutingContext.response();
response.setStatusCode(statusCode).end("Sorry! Not today");
});
See the error handling section of the Vert.x Web documentation