Charlie Fish
Charlie Fish

Reputation: 20566

Catch AWS S3 Get Object Stream Errors Node.js

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?

Upvotes: 1

Views: 4239

Answers (1)

A.Khan
A.Khan

Reputation: 4002

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
  })

Upvotes: 11

Related Questions