Mongoose ValidationError thrown instead of passed to callback, - node.js

Mongoose has started throwing errors for me instead of passing them to my callback?
var newsArticle = new NewsArticle(fields);
newsArticle.save(function(err, newsArticle) {
if(err) return next(err);
res.status(201).json(newsArticle);
});
the callback is never called, and the ValidationError is thrown, crashing the app. Why is this?
events.js:85
throw er; // Unhandled 'error' event
^
No listeners detected, throwing. Consider adding an error listener to your connection.
ValidationError: NewsArticle validation failed

Related

NestJS - Microservices - Kafka Exception Handling

I'm using NestJS to implement a microservice architecture, I'm using CLIENT app using NestJS,
The client app receives a rest request and sends to Kafka to get the result
try {
const pattern = 'findDoctors';
const payload = body;
const doctors = await lastValueFrom(
this.client.send(pattern, payload).pipe(timeout(50000)),
);
return doctors;
} catch (e) {
console.log(e);
throw new Error(e);
}
And in the microservice side (Hybrid Application for now, will remove the rest apis later)
#MessagePattern('findDoctors')
findDoctors(#Payload() message): any {
return this.doctorService.searchForDoctors(message.value);
}
async searchForDoctors(data): Promise<any[]> {
this.logger.info('Started search for doctors job');
throw 'Not Found';
}
After i throw the exception i get in the logs
node:17720) UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received an instance of Object
at Function.from (buffer.js:330:9)
at ServerKafka.assignErrorHeader (C:\Users\Desktop\Projects\node_modules\#nestjs\microservices\server\server-kafka.js:137:73)
at ServerKafka.sendMessage (C:\Users\Desktop\Projects\node_modules\#nestjs\microservices\server\server-kafka.js:119:14)
at C:\Users\Desktop\Projects\node_modules\#nestjs\microservices\server\server-kafka.js:81:31
at C:\Users\Desktop\node_modules\#nestjs\microservices\server\server.js:46:31
at processTicksAndRejections (internal/process/task_queues.js:79:11)
(node:17720) 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: 3)
(node:17720) [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 the client side just waits to timeout and never receive an exception response from the micro service
Tried using RpcException but it's the same
Found the answer
used
return new RpcException('not found');
instead of
throw new RpcException('not found')
throwing the exception needs an exception filter to catch it
#Catch(RpcException)
export class ExceptionFilter implements RpcExceptionFilter<RpcException> {
catch(exception: RpcException, host: ArgumentsHost): Observable<any> {
return throwError(exception.getError());
}
}
and in the client side you can catch the error when using filters and return a normal http exception, or use filters on that too
#Post('/search')
async findAll(#Body() body) {
console.log('Sending kafka msg');
try {
const doctors = await this.doctorService.findDoctors(body);
return doctors;
} catch (e) {
console.log(e)
throw new HttpException({
status: '500',
error: e.message,
}, 500)
}
}

Try to cach UnhandledPromiseRejectionWarning discord.js

i'm trying to catch an discord.js error
This error pops up when internet is off, but i want some clean code instead this messy one...
How can i catch this?
I did really try everything..
code:
(node:11052) UnhandledPromiseRejectionWarning: Error: getaddrinfo ENOTFOUND disc
ordapp.com
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:66:26)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:11052) 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 termin
ate the node process on unhandled promise rejection, use the CLI flag `--unhandl
ed-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejecti
ons_mode). (rejection id: 2)
(node:11052) [DEP0018] DeprecationWarning: Unhandled promise rejections are depr
ecated. In the future, promise rejections that are not handled will terminate th
e Node.js process with a non-zero exit code.
i did try this at the very top :
process.on('uncaughtException', function (err) {
//console.log('### BIG ONE (%s)', err);
console.log("555")
});
aswell this one :
client.on('error', error => {
if (error.code === 'ENOTFOUND') {
console.log(no internet!!)
}
});
I also did try this to see where its from, but nothing shows up its still the same
try {
var err = new Error("my error");
Error.stackTraceLimit = infinity;
throw err;
} catch(e) {
console.log("Error stack trace limit: ")
console.log(Error.stackTraceLimit);
}
Error stack trace limit:
10
(node:11008) UnhandledPromiseRejectionWarning: Error: getaddrinfo ENOTFOUND disc
ordapp.com
here is the code i use for now what gives the error.
i just want to catch the error in something like this: (No connection)
const Discord = require('discord.js')
const client = new Discord.Client({ autoReconnect: true });
const opn = require('opn')
const getJSON = require('get-json')
const request = require('request');
const config = require("./config/config.json");
const pushbullet = require("./config/pushbullet.json");
const addons = require("./config/addons.json");
const Registration = require("./config/Reg.json");
client.on('uncaughtException', function (err) {
//console.log('### BIG ONE (%s)', err);
console.log("555")
});
client.login(config.Settings[0].bot_secret_token);
I would try to wrap it with try/catch.
And maybe add the following code to understand better what is happening.
Error.stackTraceLimit = Infinity
Reference:
https://developer.mozilla.org/en-US/docs/Archive/Web/JavaScript/Microsoft_Extensions/Error.stackTraceLimit
Remember to remove it after the problem solved, this is not suitable for production use.
Well i solved it!!
I put this on top and its all solved.
process.on('unhandledRejection', error => {
if (error.code === "ENOTFOUND") { console.log ("No internet connection")}
if (error.code === "ECONNREFUSED") { console.log ("Connection refused")}
//console.log('Unhandled promise rejection:', error.code);
});

How can I gracefully handle a failed tcpSocket.connect attempt?

The following code causes an error when there is no existing TCP server to communicate with on the specified host:
const net = require('net');
const argv = require('minimist')(process.argv.slice(2));
try {
var tcpSocket = new net.Socket();
tcpSocket.connect(argv.tcpport, argv.tcphost, function onConnected() {
console.log('connected');
tcpSocket.on('data', function onIncoming(data) {
console.log(data);
});
tcpSocket.on('close', function onClose(data) {
tcpSocketConnected = false;
});
tcpSocketConnected = true;
});
} catch (err) {
console.log("PRINT ME: ", err);
}
Error:
events.js:183
throw er; // Unhandled 'error' event
^
Error: connect ECONNREFUSED 127.0.0.1:1906
at Object._errnoException (util.js:992:11)
at _exceptionWithHostPort (util.js:1014:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1186:14)
I am unable to catch the error even though I wrap the code in a try...catch.
Why does my catch block not catch the error?
How can I gracefully handle the error?
You should be able to explicitly handle the error event using event emitter api (same way as you handled close and data):
tcpSocket.on('error', handleError)
From Docs:
Event: 'error'#
Added in: v0.1.90
<Error>
Emitted when an error occurs. Unlike net.Socket, the 'close' event
will not be emitted directly following this event unless server.close()
is manually called. See the example in discussion of server.listen().

Mongoose after upgrade to 4.5.9 with mongo 3.2.0 giving unhandled error

To gain performance that mongo 3.2 is providing we have upgraded to mongo 3.2 from 3.0 with mongoose version upgraded from 3.8.8 to 4.5.9. But we are getting following errors and not able to find out the reason for it.
events.js:141
throw er; // Unhandled 'error' event
^
TypeError: callback.apply is not a function
at Query.<anonymous> (/home/ubuntu/urbanclap/service-market/node_modules/mongoose/lib/model.js:3327:16)
at /home/ubuntu/urbanclap/service-market/node_modules/mongoose/node_modules/kareem/index.js:259:21
at /home/ubuntu/urbanclap/service-market/node_modules/mongoose/node_modules/kareem/index.js:127:16
at doNTCallback0 (node.js:408:9)
at process._tickCallback (node.js:337:13)
error: Forever detected script exited with code: 1
error: Script restart attempt #11
Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html
From Mongoose code I got to know that it is emitting error with following code.
Model.$wrapCallback = function(callback) {
var _this = this;
return function() {
try {
callback.apply(null, arguments);
} catch (error) {
_this.emit('error', error);
}
};
};
It might be because of the mongoose latest version, we have to explicitly add the promises.
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://10.7.0.3:27107/data/db');
http://mongoosejs.com/docs/promises.html

mongodb insert into collection with nodejs

I'm trying to insert into collection but I get error not sure why. here is what I tried to do
db.collection("book", function(err, collection){
if(err){
console.log(err);
}
collection.insert({"name":req.query.file.split(".")[0],"length":response}, function(err,book) {
if(err){
console.log(err);
}
return callback(null);
console.log(book);
});
return callback(null);
});
I'm trying to insert a "book" into book collection... as I saw in mongo document .collection and .insert requires callback.
and my error is
events.js:72
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE
at errnoException (net.js:900:11)
at Server._listen2 (net.js:1038:14)
at listen (net.js:1060:10)
at net.js:1134:9
at dns.js:72:18
at process._tickCallback (node.js:415:13)
and I'm not sure what I'm doing wrong, thanks!
Are you sure that it is because of insert? It is typical unhandled exception in case you try to start node.js process that listens for the same port as other process( or the same copy of this node.js process)

Resources