ECONNRESET Aborted error randomly during node process - node.js

My node js application ( a discord bot ) keeps crashing with the Error: aborted message and code ECONNRESET. I have some some digging and it seems that the issue occurs when the other end of a TCP connection hangs up abruptly.
The error message I always get:
Error: aborted
at connResetException (node:internal/errors:631:14)
at TLSSocket.socketCloseListener (node:_http_client:438:27)
at TLSSocket.emit (node:events:388:22)
at node:net:666:12
at TCP.done (node:_tls_wrap:573:7) {
code: 'ECONNRESET'
}
As you can see the error message is not very useful and doesn't provide any informatino as to where the error happened. I am getting the error through the node process.on('uncaughtException', err => {}) exception handler.
I am using discord.js ^12.5.1 node 15.4.0 and axios ^0.21.1 although the error seems to occur randomly and looking through the logs there is never a specific function call that triggers it and sometimes it happens whilst no functions have even been called.
The error happens sporadically as well. Sometimes it happens once a day and other times it will happen 5 times in an hour.
I should also add I am using the Heroku free tier for hosting,
If anyone could shed some light that would be very useful.

Related

WebHook call failed. Error: DEADLINE_EXCEEDED, State: URL_TIMEOUT, Reason: TIMEOUT_WEB calling from node

I am not sure what mistake I am doing. I have create a ChatBot in google dialog flow and did setup of WebHook in my local. Once I am hitting from dialogbox then reuqest is landing to code and processed successfully but in Dialogflow response I am getting failure due to some TimOut exception, there a way to fix this . I am facing WebHook call failed. Error: DEADLINE_EXCEEDED, State: URL_TIMEOUT, Reason: TIMEOUT_WEB calling from node.
Below is the index.json snippet :
Below is the console log
At the end of the function you need to resolve the promise.
return Promise.resolve();
Additionally, you're probably already handling errors but in a Firebase Function, if you need to throw an error, you can do that simply this way:
throw new functions.https.HttpsError(
'internal',
'Woops, that should not happen.',
);

Error messages displayed when a test fails using MochaJs

I am using Mocha with chai to perform unit testing. But I can't comprehend the error messages displayed when a test fails.
For instance, I have a simple api, that only accepts alpha characters for certain inputs. If the user attempts to submit something like "3rror", the api will return a status of 403, or some other error code.
With Mocha I can assert something like : response.should.have.status(403); to check the server is catching and serving invalid requests appropriately.
However; with Mocha, I am completely lost when trying to reason out why or what caused an error to occur. Did I write a bad test, did my sanitization/validation middleware fail, am I even connected to my server, or am I failing to handle invalid requests and/or errors appropriately?
Below is an example of an error message Mocha provides for the mentioned case.
Uncaught TypeError: Cannot read properties of undefined (reading 'should')
at C:\...\test.js:53:43
at Test.Request.callback (node_modules\chai-http\node_modules\superagent\lib\node\index.js:716:12)
at IncomingMessage.<anonymous> (node_modules\chai-http\node_modules\superagent\lib\node\index.js:916:18)
at IncomingMessage.emit (node:events:539:35)
at endReadableNT (node:internal/streams/readable:1345:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
I understand it gave the wrong status code, but these error messages don't really help me understand what went wrong. Did I just goof an write a bad test, or did my app fail? So I am here to ask for help.
How can I better understand these errors reported when a test fails using Mocha?

how to debug error from stripe API call? need a node.js stacktrace across event emitter?

I have a node webapp that makes various API calls to Stripe using the stripe npm package. Sometimes I get errors like the one below. Notice that the stacktrace is truncated so that I cannot see which stripe API call causes the error and I also cannot see where in my app this API call is made.
Is there anything I can do to get better error stacktraces?
Error: Missing required param: customer.
at Function.generate (/home/molsson/dv/foobar/node_modules/stripe/lib/Error.js:39:16)
at IncomingMessage.<anonymous> (/home/molsson/dv/foobar/node_modules/stripe/lib/StripeResource.js:175:33)
at Object.onceWrapper (events.js:299:28)
at IncomingMessage.emit (events.js:215:7)
at IncomingMessage.EventEmitter.emit (domain.js:476:20)
at endReadableNT (_stream_readable.js:1183:12)
at processTicksAndRejections (internal/process/task_queues.js:80:21)
Note: the error itself is just an example. I have already fixed it. I just want to get better stacktraces or a better method of debugging these types of errors quickly.
I'm pretty sure my node version has async stacks by default:
$ node --version
v12.12.0
$ node -p process.versions.v8
7.7.299.13-node.12
I tried running with NODE_OPTIONS='--trace-warnings --stack-trace-limit=9999' but it didn't help.
Does it exists some kind of "async stacktraces across event emitters" debugging thing?
I found a good answer to this question myself. The stripe library fires and event before making a new API request, so you can print a stacktrace from there:
stripe.on('request', request => {
const currentStack = (new Error()).stack.replace(/^Error/, '')
console.log(`Making Stripe HTTP request to ${request.path}, callsite: ${currentStack}`)
})
I added a STRIPE_API_TRACING option to my app that I can turn on if I experience errors without stacks. With the tracing on I can just scroll a bit up in the log and see what API calls was dispatched just before the error happened.

NodeJS ETIMEDOUT2

My sockets keep on erroring out with ETIMEDOUT2. I know what ETIMEDOUT means, but I have never heard of ETIMEDOUT2.
From reading the NodeJS documentation I thought this list was a comprehensive list of system error messages.
I have also checked out the libuv repository and its documentation, but no sign of this error message.
I've searched the NodeJS repo for the error and googled as well, but no one else seems to have ever encountered the message either.
This is on an Ubuntu system.
Sample log:
[DATE] [ERROR] connection - { message: 'socket error',
uidx: XXXX,
dest_id: 'XXXXX',
error: 'ETIMEDOUT2' }

Node Exception Handling

What is the best way in node to handle unhandled expections that are coming out of core node code? I have a background process that runs and crawls web content and will run for long periods of time without issue, but every so often an unexpected exception occurs and I can't seem to gracefully handle it. The usual culprit appears to be some networking issue (lost connectivity) where the http calls I'm making fail. All of the functions that I have created follow the pattern of FUNCTION_NAME(error, returned_data), but in the situations where the error occurs I'm not seeing any of the functions I created in the call stack that is printed out, instead its showing some of the core node modules. I'm not really worried about these infrequent errors and their root cause, the purpose of this posting is just trying to find a graceful way of handling these exceptions.
I've tried putting a try/catch at the top level of my code where everything runs under but it doesn't seem to capture these exceptions. Is it good practice in node to use try/catch within all the lower level functions that use any core code? Or is there some way to globally capture all unhandled exceptions?
Thanks
Chris
UPDATED TO ADD STACK
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: connect Unknown system errno 10060
at errnoException (net.js:642:11)
at Object.afterConnect [as oncomplete] (net.js:633:18)
is there some way to globally capture all unhandled exceptions?
You can catch all exceptions using process.on('uncaughtException'). Listening to this event will avoid the default action of printing the stack and exiting. However be conscious that ignoring exceptions may lead to problems in your app execution.
Link: http://nodejs.org/docs/latest/api/process.html#process_event_uncaughtexception
Pay attention to the documentation advice:
Note that uncaughtException is a very crude mechanism for exception handling. Using try / catch in your program will give you more control over your program's flow. Especially for server programs that are designed to stay running forever, uncaughtException can be a useful safety mechanism.
To catch network errors and avoid the default behavior (printing stack and exit) you have to listen to "error" events.
For example
var net = require('net');
var client = net.connect(80, 'invalid.host', function () {
console.log("Worked");
})
client.on('error', console.log);
I wrote about this recently at http://snmaynard.com/2012/12/21/node-error-handling/. A new feature of node in version 0.8 is domains and allow you to combine all the forms of error handling into one easier manage form. You can read about them in my post and in the docs.
You can use domains to handle callback error arguments, error event emitters and exceptions all in one place. The problem in this specific case is that when you dont handle an error event emitter, node by default will print the stack trace and exit the app.
I've put together a quick error handling file which logs and emails me whenever an unhandled exception is thrown. it then (optionally) tries to restart the server.
Check it out!

Resources