Error not being handled in chain of promises - node.js

I am fairly new to Node and am currently trying to tweak an existing project. Part of this uses the follow-redirects package to make HTTP(S) requests to fetch an image.
Occasionally my service crashes with the following trace:
events.js:174
throw er; // Unhandled 'error' event
^
Error: socket hang up
at createHangUpError (_http_client.js:323:15)
at Socket.socketOnEnd (_http_client.js:426:23)
at Socket.emit (events.js:203:15)
at Socket.EventEmitter.emit (domain.js:448:20)
at endReadableNT (_stream_readable.js:1145:12)
at process._tickCallback (internal/process/next_tick.js:63:19)
Emitted 'error' event at:
at ClientRequest.eventHandlers.(anonymous function) (/home/.../node_modules/follow-redirects/index.js:13:24)
at ClientRequest.emit (events.js:198:13)
at ClientRequest.EventEmitter.emit (domain.js:448:20)
at Socket.socketOnEnd (_http_client.js:426:9)
at Socket.emit (events.js:203:15)
[... lines matching original stack trace ...]
at process._tickCallback (internal/process/next_tick.js:63:19)
I assume this means that I am dropping the error which comes back from the HTTP request.
Here is my function where I make the request:
function fetchRemote (imageUrl) {
let options = ...
return new Promise((resolve, reject) => {
https.get(options, resolve);
});
}
And it's called using a chain of promises.
fetchRemote(imageUrl)
.then(getResizeStream)
.then(storeImage)
.then(finished)
.catch(error);
function error (err) {
reject(new Error(`Failed: ${err.message}`));
};
Is there a logic pathway I'm missing, or should this properly catch the error? Or is the issue actually in the follow-redirects package?

Sockets are "event" emitter based and not promises. You need to handle errors on sockets by doing something along the lines of
socket.on('error',function(err){ /* handle error */});
// for you:
https
.get(options, resolve)
.on('error', err => {
reject(err);
});

Related

Node.js websocket unhandeled error events.js websocket.js

I am using express webserver with node.js and the standard websocket require('ws');
Now it happens sometimes when internet connection is lost, i think that is the main reason when this happen, i am getting then a error message and the script stops to run:
events.js:287
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at TLSWrap.onStreamRead (internal/stream_base_commons.js:205:27) Emitted 'error' event on WebSocket instance at:
at WebSocket.finalize (C:\Users\ABC\Desktop\Websocket\node_modules\ws\lib\WebSocket.js:182:41)
at TLSSocket.emit (events.js:310:20)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
at processTicksAndRejections (internal/process/task_queues.js:84:21) { errno: 'ECONNRESET',
code: 'ECONNRESET', syscall: 'read' }
In the websocket client code i have also write a console.log or error events, see my code below:
ws.on('message', function incoming(data)
{
const obj = JSON.parse(data);
console.log("Stream: "+obj["k"].s+" "+obj["k"].i+" closeprice "+obj["k"].c+"\n");
});
ws.on('error', function(e){
console.log("stream error "+e);
});
the question is if i can do something to prevent this behavior? I normaly know that this problems happen when you dont console.log error events but for me it looks like i am doing that already. Maybe do i need to make changes in the ws module files?

Node JS trying to download a number of images. Stream seems to keep being closed

I'm looping through quite a lot of images to download from a website using this function:
const fileGet = (url, path, callback) => {
request.head(url, (err, res, body) => {
request(url)
.pipe(fs.createWriteStream(path))
})
.on('error', function(err, res) {
console.log(err + res)
})
}
It seems to get so far and then the stream seems to be closed. I've been doing some googling and people mention it could be trying to resolve too many dns lookups in a given time.
This is the error I'm getting:
node:events:371
throw er; // Unhandled 'error' event
^
Error: getaddrinfo ENOTFOUND www.domain.com
at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:71:26)
Emitted 'error' event on Request instance at:
at Request.onerror (node:internal/streams/legacy:62:12)
at Request.emit (node:events:394:28)
at Request.onRequestError (C:\Scraper\node_modules\request\request.js:877:8)
at ClientRequest.emit (node:events:394:28)
at TLSSocket.socketErrorListener (node:_http_client:447:9)
at TLSSocket.emit (node:events:394:28)
at emitErrorNT (node:internal/streams/destroy:193:8)
at emitErrorCloseNT (node:internal/streams/destroy:158:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
errno: -3008,
code: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'www.domain.com'
}
I've tried hard coding the IP/Host name in my Hosts file, and tried putting a pause in the requests, same problem. I've also upgraded to the last version of Node (16.4.0)
Still the same.
There is a lot of debate about this issue online. Has it even been resolved?
Thanks.
If anybody is interested, it was a DNS lookup issue, and sorted it by using DNS Cache.
Just wrapper my whole download process with an initial look up, and the rest ran like a dream.

UnhandledPromiseRejectionWarning WebSocket in NodeJs although implemented on error

I'm having issues with a webSocket connection (nodejs, ws). Now and then i see the following error message at the console and i don't know where it comes from. Seems like there is a problem with the internet connection or DNS server at the moment the error is raised. The application should be able to handle broken internet connection. At the moment the error is raised, the whole application stops.
The Error at the console:
(node:14656) UnhandledPromiseRejectionWarning: Error: Query timed out
at DNS._ontimeoutCheck (C:\Users\XYZ\Documents\nodedev\Server-DEV\node_modules\dns-socket\index.js:123:18)
at Timeout.ontimeoutCheck (C:\Users\XYZ\Documents\nodedev\Server-DEV\node_modules\dns-socket\index.js:53:10)
at listOnTimeout (internal/timers.js:531:17)
at processTimers (internal/timers.js:475:7)
(node:14656) UnhandledPromiseRejectionWarning: Error: Query timed out
Error: getaddrinfo ENOTFOUND connect.server.cloud
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:60:26)
Emitted 'error' event on ServerCloud instance at:
at ServerCloud.<anonymous> (C:\Users\XYZ\Documents\nodedev\Server-
DEV\plugins\inbound\ks\ks.js:353:18)
at WebSocket.emit (events.js:223:5)
at ClientRequest.<anonymous> (C:\Users\XYZ\Documents\nodedev\Server-
DEV\node_modules\ws\lib\websocket.js:554:15)
at ClientRequest.emit (events.js:223:5)
at TLSSocket.socketErrorListener (_http_client.js:406:9)
at TLSSocket.emit (events.js:223:5)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
at processTicksAndRejections (internal/process/task_queues.js:81:21) {
errno: 'ENOTFOUND',
code: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'connect.server.cloud'
i have implemented the .on('error', (err) => { method in my code:
this._ws.on('error', function (error) {
this.connected = false;
this.emit('error', error);
this.LogAtMain('WebSocket Error: ' + error.message);
console.log('Error message: ' + error.message);
});
How can i catch this error unlike implementing the on(error) hook?
Somewhere in your code, you forgot to handle a promise rejection. That is why you are getting that error.
You can handle UnhandledPromiseRejectionWarning like this:
process.on('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection at: Promise', p, 'reason:', reason.stack);
// application specific logging, throwing an error, or other logic here
});

Cant find origin of Unhandled 'error' event ETIMEDOUT

I am building an application that is communicating with a local server through http requests, I decided to do a "real" test and it keeps throwing errors, but I cant track where the error is coming from, the stacktrace doesnt tell me where it originates from (in my app).
When I start my app it works for 20-30 seconds, it manages to get/send data to that local webserver, but after 20-30 seconds I get the following error:
events.js:287
throw er; // Unhandled 'error' event
^
Error: connect ETIMEDOUT 192.168.55.213:80
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16)
Emitted 'error' event on ClientRequest instance at:
at Socket.socketErrorListener (_http_client.js:426:9)
at Socket.emit (events.js:310:20)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
errno: 'ETIMEDOUT',
code: 'ETIMEDOUT',
syscall: 'connect',
address: '192.168.55.213',
port: 80
}
I have tried all my http requests in a try/catch block and log the errors to try and pinpoint where it originates from but nothing, the try/catches dont work, because the error is still being thrown, so it is not from within my http requests and I cant figure out the origin of the error. My requests look something like this:
async RequestFunction(requesturl) {
return new Promise((resolve, reject) => {
try {
http.get(requesturl, (resp) => {
let data = "";
resp.on('data', (chunk) => data += chunk)
resolve(data)
});
} catch (error) {
console.log(`${requesturl}+${error.code}`);
}
}
}
But the catch never gets triggered. I am guessing that mostly what I am asking for is how to track where the error is originating from?
I have also tried wrapping my Request function in every place where I am calling and awaiting it with a try/catch block, same thing.

I can not handle error event in net.createServer

proxy multiple proxies by net.createServer
here is my all code
var proxies='127.0.0.1:4444,127.0.0.1:4443,127.0.0.1:4442'.split(',');
var net = require('net');
function randgetir(){
d=proxies[Math.floor(Math.random() * proxies.length)].split(':');
return [d[0],d[1]];
}
var cre=net.createServer(function(from) {
var prgs=randgetir();
var to = net.createConnection({host: prgs[0],
port: prgs[1]
}).on('error', function(error) {
});
from.pipe(to);
to.pipe(from);
}).on('error', function(error) {
});
cre.listen("56666");
when i run the code sometimes i get
Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:162:27)
Emitted 'error' event at:
at errorOrDestroy (internal/streams/destroy.js:98:12)
at Socket.onerror (_stream_readable.js:720:7)
at Socket.emit (events.js:197:13)
at emitErrorNT (internal/streams/destroy.js:82:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
at processTicksAndRejections (internal/process/next_tick.js:76:17)
error and my app just crash and exit but as you see i handle all the error events,
what may i be doing wrong?
The problem is that there is no error handler attached to the incoming message stream. You could attach a handler like this:
from.on('error', function(e){ ...}))
.pipe(to);
Maybe check out this post on stackoverflow for more information regarding error handling with streams/pipes: Error handling with node.js streams

Resources