Tuan Anh Tran
Tuan Anh Tran

Reputation: 7247

How to trace uncaughtException exception in Node.js?

How do I find out where that error is originated from ? The error output doesn't look very descriptive. From the log, it was ECONNRESET error.

process.on('uncaughtException', function(err) {

})

Upvotes: 2

Views: 4755

Answers (1)

JasonS
JasonS

Reputation: 7733

I had this same problem.

What made it hard, is it's not in my code, but in a library i use.

So as you also have found out, the stack trace provided isn't helpful at all. Even after installing a package like longjohn your stack track from this server crash is all internal:

Error: read ECONNRESET
    at TCP.onStreamRead (internal/stream_base_commons.js:111:27)
---------------------------------------------
    at _destroy (internal/streams/destroy.js:34:15)
    at Socket._destroy (net.js:607:3)
    at Socket.destroy (internal/streams/destroy.js:32:8)
    at TCP.onStreamRead (internal/stream_base_commons.js:111:19)
Waiting for the debugger to disconnect...

You need to handle the emitter.on("error") events, as basically described here: Node js ECONNRESET

In my situation I was able to reproduce the error by sending an invalid password via a curl request. and was able to solve because the library I'm uses exposes the request object for incoming requests.

So with that, here's my solution code:

function onRequest(requestDetails){
            requestDetails.request.connection.on( "error", ( _err ) => {
                log.error( "request.connection.on.error", _err );
            } );

            let reqSocket = requestDetails.request.socket;
            reqSocket.on( "error", ( _err ) => {
                log.error( "request.socket.on.error", _err );
                reqSocket.destroy( _err );
            } );

            requestDetails.request.on( "error", ( _err ) => {
                log.error( "request.on.error", _err );
            } );

            // my actual request handling code goes here.....
}

I also added error handler for the server object, though that wasn't needed in this case:

    server.on( 'requestFailed', ( { request, error }: any ) => {
        log.error( `Request ${ request.url } failed`, error );
    } );

    server.on( 'error', ( ...args: any[] ) => {
        log.error( "server.on.error", args );
    } );

    server.on( 'connection', function ( socket ) {
        socket.on( 'error', function ( err ) {
            log.error( "Client socket error:", err );
            socket.destroy( err );
        } );
    } );

Upvotes: 0

Related Questions