I am getting an unhandled error but not sure where it's coming from. My app has several http.request(options, callback).end() in different methods, with the callback's trapping "uncaughtException" and "error". I'd like to know which of my methods initiated this issue. Below is the error I get. It is random. Any ideas how to track this down? I was hoping for some global way of trapping unhandled errors.
events.js:85
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at exports._errnoException (util.js:746:11)
at TCP.onread (net.js:559:26)
ECONNRESET means that the other side of the TCP connection is aborted. You could look at the server logs, but since it was random times this makes me think that the server becomes overloaded and kills a few connections.
If you're starting a process at any point in the process try the below:
process.on('uncaughtException', function (err) {
console.error(err.stack);
console.log("Node NOT Exiting...");
});
attach a
request.on('error', function(err) {
// Handle error
});
to your requests.
You can also catch uncaught errors for the process:
process.on('uncaughtException', function(err) {
console.log('Caught exception: ' + err);
});
This error as it reads states the connection was reset, so its definitely one of the requests.
Related
In my server.js file i'm trying to log errors and not cause them to crash the app, this is the code im using
const server = app.listen(3000, () =>
console.log('Server Up and running')
);
process.on('unhandledRejection', (err, promise) => {
console.log(`Error: ${err}`);
server.close(() => process.exit(1));
})
when i produce an error instead of it logging the error and closing the server it just logs the error how it normally would and causes the app to crash. If you need more info let me know. Sorry if this is a dumb question
I suppose you know the difference between Unhandled Rejection and Uncaught Exception.
it just logs the error how it normally would
Because you're console logging the same error object!
Also don't use process.exit(). Because you might lose your logs. read more
Express docs explained how to do graceful shutdown, you can use similar approach.
I'm using Winston to log to file / seq information I specifically log using log.info or some other level. But I've noticed that when an unhandled exception occurs, it's not logged... I'm not really familiar with Nodejs and HAPI (need to perform some activity while my colleagues are on vacation).. but I was wondering if there's a sort of middleware where I can attach and let Winston log all HAPI stuff.
Thanks in advance
You can listen on uncaughtException and/or unhandledRejection of your current Node.js process to call you logger (here I simply called console.log):
process.on('uncaughtException', (err, origin) => {
console.log('Caught exception:', err, 'Exception origin:', origin);
});
process.on('unhandledRejection', (reason, promise) => {
console.log('Unhandled Rejection at:', promise, 'reason:', reason);
});
However:
uncaughtException is a crude mechanism for exception handling intended to be used only as a last resort.
...
The correct use of uncaughtException is to perform synchronous cleanup of allocated resources (e.g. file descriptors, handles, etc) before shutting down the process. It is not safe to resume normal operation after uncaughtException.
Read also Catch all uncaughtException for Node js app.
I build a server which get many requests and response to them.
In some cases, there is an error which cause the server to crush:
events.js:72
throw er; // Unhandled 'error' event
^
Error: ENOENT, open '/mnt/ace/0/file'
I have two problems:
the stack trace doesn't give me any information about the line in my application that cause this exception (I can't do manually debugging because it happens just when I get 1000 request or more).
I don't want that my server ould crush. I prefer that it will raise an exception, but will continue to work.
What the best implementation for this?
You can listen for that kind of stuff and not have it crash the app, but that's not always a great idea.
process.on('uncaughtException', function(err) {
console.log('Something bad happened');
console.log(err.stack);
});
In your case, have you tried checking ulimit settings? You may be having problems opening file handles under loads of 1000+.
Another way of thinking about this is to use domains (if you're using >= 0.8). Domains give you a finer grain of control over how you handle errors based on what contexts cause them.
var domain = require('domain').create();
domain.on('error', function(err) {
console.log(err);
});
domain.run(function() {
// Your code that might throw
});
Please note that the above "possible answer" questions does not contain an answer to my question. I am using require("http"). In that question the person is taking a socket input variable that they can put a handler on. I do not have the same variable.
I have a very simple server that I have written in Node.
var http = require("http");
var sys = require("sys");
var httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer({
target: "someServer"
});
http.createServer(function(request, response) {
try {
proxy.web(request,response);
} catch (err) {
sys.puts("I caught an error!");
}
}).listen(5000);
When I leave my app running, it crashes. My command line says:
events.js:72
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at errnoException (net.js:900:11)
at TCP.onread (net.js:555:19)
It seems to crash not when server is serving files, but when it is waiting for a long time between requests.
While my code is a little more complex, I do have error catching on every callback.
Why is it crashing? What can I do?
In node, sprinkling try and catch everywhere is not the same as catching every error. (And in most cases, doing so is useless.) Asynchronous operations cannot throw useful exceptions because control long ago left the block of code that invoked the operation.
Instead, many objects emit an error event. The error event is a special case in that node will throw a "real" exception if there are no listeners for the event. Because this exception is thrown from code you do not and cannot control (ie wrap with try/catch), it goes uncaught and the process ends.
So if you do not add an error listener to sockets, a socket error will bring down the entire app.
However, your unhandled error is not coming from your http requests. The http module adds an error handler to every socket automatically, and re-emits the error as a clientError event on the Server. Because EventEmitters only throw when the event is named error, the fact that you don't handle clientError does not matter.
If we read http-proxy's documentation, we see that it also throws an error event, and you aren't listening for it. Thus, your app dies whenever there's an error fetching something from an upstream server.
Add an error handler.
proxy.on('error', function (err, req, res) {
res.writeHead(500, {
'Content-Type': 'text/plain'
});
res.end('Something went wrong.');
console.error(err);
});
Any time you see this error ("// Unhandled 'error' event"), it means you need to find out what is emitting an error event and add a listener to handle the error.
In my node.js app which uses the cluster module, I'm intermittently seeing errors like this:
events.js:71
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at errnoException (net.js:863:11)
at TCP.onread (net.js:524:19)
This brings down my whole app, and so far the only way I've been able to deal with these is by binding a process.on('uncaughtException'). I'd like to figure out the underlying cause, but the above stack trace is pretty useless.
Is there some way to figure out what's causing these exceptions?
I should note that I'm seeing these only in the cluster master, not the workers, which leads me to suspect that they have something to do with the way the cluster modules does its magic in distributing connections to workers.
This answer was helpful: https://stackoverflow.com/a/11542134/233370
Basically, I installed longjohn and was then able to get the full async stack trace to figure out the underlying cause (rabbit.js in my case).
It seems that express enabled keep-alive by default.
In order to close connection after response you can add
res.set("Connection", "close");
Alternatively you can add a middleware in your app to close connection after each response:
app.use(function(req, res, next) {
res.set("Connection", "close");
next();
});