1

I'm trying to build an Express server that will send items in a S3 bucket to the client using Node.js and Express.

I found the following code on the AWS documentation.

var s3 = new AWS.S3({apiVersion: '2006-03-01'});
var params = {Bucket: 'myBucket', Key: 'myImageFile.jpg'};
var file = require('fs').createWriteStream('/path/to/file.jpg');
s3.getObject(params).createReadStream().pipe(file);

I have changed I slightly to the following:

app.get("/", (req, res) => {
    const params = {
        Bucket: env.s3ImageBucket,
        Key: "images/profile/abc"
    };
    s3.getObject(params).createReadStream().pipe(res);
});

I believe this should work fine. The problem I'm running into is when the file doesn't exist or S3 returns some type of error. The application crashes and I get the following error:

NoSuchKey: The specified key does not exist

My question is, how can I catch or handle this error? I have tried a few things such as wrapping that s3.getObject line in a try/catch block, all of which haven't worked.

How can I catch an error and handle it my own way?

Charlie Fish
  • 18,491
  • 19
  • 86
  • 179

1 Answers1

11

I suppose you can catch error by listening to the error emitter first.

s3.getObject(params)
  .createReadStream()
  .on('error', (e) => {
    // NoSuchKey & others
  })
  .pipe(res)
  .on('data', (data) => {
    // data
  })
A.Khan
  • 3,826
  • 21
  • 25