最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Catch AWS S3 Get Object Stream Errors Node.js - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question asked Jan 13, 2019 at 23:18 Charlie FishCharlie Fish 20.6k23 gold badges106 silver badges199 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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
  })
发布评论

评论列表(0)

  1. 暂无评论