0

There is an image object in my AWS S3 bucket called "aws-image". When I request this image I get the object but if I request wrong object "aws-imagee" gives "Access Denied" error and crushes the node server.

What's the problem here? When I request an object that is not in the bucket I expect my server to contunie running.

const getFileStream = fileName => {
  const downloadParams = {
    Key: fileName,
    Bucket: bucketName
  }

  return s3.getObject(downloadParams).createReadStream()
}

app.get('/aws-images/:id', jsonParser, (req, res) => {
  const id = req.params.id

  try {
    const readStream = getFileStream(id)
    readStream.pipe(res)
  } catch (err) {
    res.json(err)
  }
})

Tried this try-catch block and still the "Access Denied" error of non existant object crushes the server.

Erenn
  • 625
  • 6
  • 18
  • 2
    why dont you un your backend code with exception handling using try , catch – Jatin Mehrotra Jun 10 '21 at 05:42
  • I have added the try-catch code block. Still "Access Denied" error crushes the server. – Erenn Jun 11 '21 at 01:44
  • i think IAM user doestn't have a policy attached to it. tryassigning AmazonS3FullAccess policy and try posting your error message too – Jatin Mehrotra Jun 11 '21 at 02:39
  • Gave full access to anything. Now I am getting the error of ''The specified key does not exist.' – Erenn Jun 11 '21 at 02:43
  • it simply means that your file does not exist up within the S3 bucket, now i think you can work with your try catch block and figure out a logic what to do if such error happens – Jatin Mehrotra Jun 11 '21 at 02:48
  • 1
    Well tried to copy solutions from this question: https://stackoverflow.com/questions/43799246/s3-getobject-createreadstream-how-to-catch-the-error – Erenn Jun 11 '21 at 02:58

1 Answers1

1

Solutions is not elegant. Very dirty actually. I coudlnt seperate download function from router. This is how route looks like. Now errors doesnt crush the server. We catch the errors.

app.get('/aws-images/:id', jsonParser, (req, res) => {
  const id = req.params.id

  const downloadParams = {
    Key: id,
    Bucket: bucketName
  }

  s3.getObject(downloadParams)
    .createReadStream()
    .on('error', e => {
      // handle aws s3 error from createReadStream
      console.log(e)
      res.json(e)
    })
    .pipe(res)
    .on('data', data => {
      // retrieve data
    })
    .on('end', () => {
      // stream has ended
    })
})
Erenn
  • 625
  • 6
  • 18