Unable to catch error using try catch and Promise

Hello Guys,

Does anyone here knows how we can catch the error on the codes below. It still sending error to the server like if the file not exist, it automatically send error to server instead of using the try catch on on custom error function.

try{   
        let _process = new Promise((resolve, reject) => {
          var src = new S3S.ReadStream(s3Client, getObjectOptions);
            src
            .on('open', (object) => {
                _thisresp.writeHead(200, {
                    'Content-Type': object.ContentType,
                    'Content-Length': object.ContentLength
                });
            })
            .pipe(_thisresp)
            .on('finish', () => {
                resolve();
            })
            .on('error', (err) => {
                reject();
            });
        });
        
        return _process;
      }catch(err){
          console.log('error');
      }

Thanks for the help in advance!

Not sure I follow, but maybe put the try/catch inside the promise, and reject from the catch block? Also, reject() can take an argument.

let _process = new Promise((resolve, reject) => {
  try { /* as before */ }
  catch(err) { console.log('error'); reject(err); }
}
return _process;

hi @alan99, I tried this solution but still is showing error on console.

HTTPParser.parserOnHeadersComplete (_http_common.js:119:17)
W20191029-02:58:42.365(0)? (STDERR)     at TLSSocket.socketOnData (_http_client.js:454:20)
W20191029-02:58:42.365(0)? (STDERR)     at emitOne (events.js:116:13)
W20191029-02:58:42.366(0)? (STDERR)     at TLSSocket.emit (events.js:211:7)
W20191029-02:58:42.366(0)? (STDERR)     at addChunk (_stream_readable.js:263:12)
W20191029-02:58:42.366(0)? (STDERR)     at readableAddChunk (_stream_readable.js:250:11)
W20191029-02:58:42.366(0)? (STDERR)     at TLSSocket.Readable.push (_stream_readable.js:208:10)
W20191029-02:59:01.684(0)? (STDERR)     at Request.callListeners (/home/ubuntu/environment/jti/node_moW20191029-02:59:01.685(0)? (STDERR)     at emitOne (events.js:116:13)
W20191029-02:59:01.685(0)? (STDERR)     at HTTPParser.parserOnHeadersComplete (_http_common.js:119:17)
W20191029-02:59:01.685(0)? (STDERR)     at TLSSocket.socketOnData (_http_client.js:454:20)
W20191029-02:59:01.686(0)? (STDERR)     at emitOne (events.js:116:13)
W20191029-02:59:01.686(0)? (STDERR)     at TLSSocket.emit (events.js:211:7)
W20191029-02:59:01.686(0)? (STDERR)     at addChunk (_stream_readable.js:263:12)
W20191029-02:59:01.686(0)? (STDERR)     at readableAddChunk (_stream_readable.js:250:11)
W20191029-02:59:01.686(0)? (STDERR)     at TLSSocket.Readable.push (_stream_readable.js:208:10)
W20191029-02:59:01.686(0)? (STDERR)     at TLSWrap.onread (net.js:601:20)

Caveat: I haven’t checked your S3S code for correctness. However, you don’t use a conventional try/catch with a Promise unless you also use async/await.

For example, you could refactor your code to something like:

let _process = new Promise((resolve, reject) => {
  var src = new S3S.ReadStream(s3Client, getObjectOptions);
  src
    .on('open', (object) => {
      _thisresp.writeHead(200, {
        'Content-Type': object.ContentType,
        'Content-Length': object.ContentLength
      });
    })
    .pipe(_thisresp)
    .on('finish', () => {
      resolve();
    })
    .on('error', (err) => {
      reject(err);
    });
});

_process.then(result => {
  // do something with result
}).catch(err => {
  console.log('error', err);
});

Note that you don’t actually return a success result (resolve()) in your code, so if there is a result, you will need to provide it (resolve(someResult)).

Once the Promise is defined, you then use a Promise chain with a .catch(error....

Alternatively, given a Promise, you can use try/catch with async/await syntax. This is a bit contrived, but hopefully you’ll get the idea:

async function startProcess() {
  try {
    await _process;
  } catch (err) {
    console.log('error', err);
  }
}

startProcess();

However, don’t forget, that whether you use a Promise chain or async/await, those sections of code are completely asynchronous and will complete outside of the execution context of the surrounding code.

1 Like

thanks for the detailed answer, but that approach still showing errors on console when I tried to make the file name incorrect. What we want is to not show errors on server-console when the file name is wrong, because it cause sometimes to stop the server working or server crashing. Seems like the S3S.on('error' is the one that doesn’t work correctly. :frowning:

First, double check that you’ve got a catch block on that promise, as uncaught promise rejections can bomb the server process.

If it’s definitely happening because the error doesn’t reach this: S3S.on('error', then I’d say that might be because they attach their own 'error' listener here:

Which is on the ReadableStream instead of on the aws-sdk Request object.

You might be able to stick one on yourself before the request returns like so:

let _process = new Promise((resolve, reject) => {
  var src = new S3S.ReadStream(s3Client, getObjectOptions);
  src.req.on('error', err => reject(err));