Meteor collection update throws exception - mongodb

My code:
try {
Alerts.update({_id: alertId}, {
$set: {
number_of_new_results: 0,
number_of_stored_results: 0,
last_time_run: null
}
});
} catch (e) {
console.log(e);
}
It generates the exception:
W20160421-16:17:37.739(2)? (STDERR) C:\Users\xauxatz\AppData\Local\.meteor\packages\npm-mongo\1.4.42\npm\node_modules\mongodb\lib\mongodb\connection\base.js:246
W20160421-16:17:37.739(2)? (STDERR) throw message;
W20160421-16:17:37.740(2)? (STDERR) ^
W20160421-16:17:37.740(2)? (STDERR) RangeError: Maximum call stack size exceeded
I have absolutely no idea what's causing the problem. This particular update works other places in the code.
Edit:
The above code is running on the server, within:
if( Meteor.isServer ) {
Meteor.methods({
.....................
});
}

I found the error myself (as so often happens). The error resulted from a recursive call. The above code was called when a certain alert was updated. And the code within the function caused the alert to be updated again :-(

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.

Flutter and Dart try catch—catch does not fire

Given the shortcode example below:
...
print("1 parsing stuff");
List<dynamic> subjectjson;
try {
subjectjson = json.decode(response.body);
} on Exception catch (_) {
print("throwing new error");
throw Exception("Error on server");
}
print("2 parsing stuff");
...
I would expect the catch block to execute whenever the decoding fails. However, when a bad response returns, the terminal displays the exception and neither the catch nor the continuation code fires...
flutter: 1 parsing stuff
[VERBOSE-2:ui_dart_state.cc(148)] Unhandled Exception: type
'_InternalLinkedHashMap<String, dynamic>' is not a subtype of type
'List<dynamic>'
What am I missing here?
Functions can throw anything, even things that aren't an Exception:
void foo() {
throw 42;
}
But the on Exception clause means that you are specifically catching only subclass of Exception.
As such, in the following code:
try {
throw 42;
} on Exception catch (_) {
print('never reached');
}
the on Exception will never be reached.
It is not a syntax error to have on Exception catch as someone else answered. However you need to be aware that the catch will not be triggered unless the error being thrown is of type Exception.
If you want to find out the exact type of the error you are getting, remove on Exception so that all errors are caught, put a breakpoint within the catch and check the type of the error. You can also use code similar to the following, if you want to do something for Exceptions, and something else for errors of all other types:
try {
...
} on Exception catch (exception) {
... // only executed if error is of type Exception
} catch (error) {
... // executed for errors of all types other than Exception
}
Use:
try {
...
} on Exception catch (exception) {
... // only executed if error is of type Exception
} catch (error) {
... // executed for errors of all types other than Exception
}
The rule is that exception handling should be from detailed exceptions to general exceptions in order to make the operation to fall in the proper catch block and give you more information about the error, like catch blocks in the following method:
Future<int> updateUserById(int userIdForUpdate, String newName) async {
final db = await database;
try {
int code = await db.update('tbl_user', {'name': newName},
whereArgs: [userIdForUpdate], where: "id = ?");
return code;
}
on DatabaseException catch(de) {
print(de);
return 2;
}
on FormatException catch(fe) {
print(fe);
return 2;
}
on Exception catch(e) {
print(e);
return 2;
}
}
print("1 parsing stuff");
List<dynamic> subjectjson;
try {
subjectjson = json.decode(response.body);
} catch (_) { . // <-- removing the on Exception clause
print("throwing new error");
throw Exception("Error on server");
}
print("2 parsing stuff");
...
This works, but what is the rationale behind this? Isn't the type inconsistency an Exception?
As everybody or most of the people said, try to know exactly what error you are getting:
try{
}
catch(err){
print(err.runTimeType);
}
runTimeType will give you the type of data or exception you are getting or to put simple the exception itself.
And then do whatever you want. (Like if you are not getting the exception of what you expected, then try to fix that issue or change the exception.)
Another option is to go with general form.
Using the simple catch which will prompt every time.
The other possible reason for the catch bloc not to fire, as pointed out in this question, is missing brackets when throwing an exception.
Must write throw FormatException() instead of throw FormatException.
I had a issue with try catch but my problem was the API that I send http request, doesn't response of my request so that is why my request doesn't response anything and try catch didn't catch the error. So I suggest you to add timeout to your request so that if your api doesn't response your request after a while you can cancel your request with timeout. Here is an example how to use it;
try {
final response = await http.post(Url).timeout(Duration(seconds: 5));
} catch (error) {
print(error)
}

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.

node.js with PostgreSQL and socket.io Error: Socket is not writable

I've been playing around with socket.io and it seems to have been working nicely. Lately though, I installed postgreSQL to insert rows to the database everytime an event happens (and the event happens 2 or 3 times per second!)... Here's a snippet:
pg.connect(conString, function(err, dbClient) {
io.sockets.on("connection", function(client) {
client.on("clientSendingPlayerData", function(playerData) {
dbClient.query("insert into actions values (1)", function() {
console.log("INSERTED ROW");
});
});
});
});
We get the error:
net.js:391
throw new Error('Socket is not writable');
^
Error: Socket is not writable
at Socket._writeOut (net.js:391:11)
at Socket.write (net.js:377:17)
at [object Object].query (/homes/jjl310/node_modules/pg/lib/connection.js:109:15)
at [object Object].submit (/homes/jjl310/node_modules/pg/lib/query.js:99:16)
at [object Object]._pulseQueryQueue (/homes/jjl310/node_modules/pg/lib/client.js:166:24)
at [object Object].query (/homes/jjl310/node_modules/pg/lib/client.js:193:8)
at Socket.<anonymous> (/homes/jjl310/tradersgame/server.js:182:16)
at Socket.$emit (events.js:64:17)
at SocketNamespace.handlePacket (/homes/jjl310/node_modules/socket.io/lib/namespace.js:335:22)
at Manager.onClientMessage (/homes/jjl310/node_modules/socket.io/lib/manager.js:469:38)
Any ideas as to what's causing the problem and how it could be fixed?
I'm using the following library for postrgreSQL
https://github.com/brianc/node-postgres
pg.connect() gets a connection from the pool, dbClient is an active connection. Long running connections can timeout, error or be dropped for inactivity. You want to move pg.connect() in to the clientSendingPlayerData callback. That way a db connetion gets pull from the pool only when needed and is returned to the pool when finished.