Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

284
Views
How to throw custom error in async callout

I'm making a couple async API callouts and may throw a custom error depending on the outcome. I'm deleting Objects from S3.

try {
    await s3.deleteObject(bucketParams);
    
    //S3 API doesn't provide resp on if obj successfully deleted. Therefore, check that it doesn't exist afterwards to verify instead
    const err = await s3.headObject(bucketParams);

    if (err & err.code === 'NotFound') return { code:200, message:`${key} successfully deleted` }

    throw `Error deleting ${key}`;
  } catch (error) {
    throw new Error(500, error);
  }

So the main catch can handle any exceptions thrown by those couple API callouts (error with network, bad key, bad authorization, etc..)

However, if the object didn't actually get deleted (so if it still exists)..I throw a custom error to get reported back to end user.

My question is if there's a better pattern to just throwing a custom error in your try and then having it get slurped up by your catch.

Thanks!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can do a lot to be honest, you just need to work out what you want to capture. Heres a basic example. If you were using TypeScript you would get more power and type safety

class S3ObjectNotFound extends Error {
  // Add other attributes you might like
  code

  constructor(message) {
    super(message)
    this.name = 's3/object-id-not-found'
    this.code = 404
  }
}

const someFunction = async (bucketParmas, key) => {
  try {
    try {
      await s3.deleteObject(bucketParams)
    } catch (s3Error) {
      throw new S3ObjectNotFound(`Object with id ${bucketParmas} was not found`)
    }

    const err = await s3.headObject(bucketParams)

    if (err && err.code === 'NotFound') {
      return { code: 200, message: `${key} successfully deleted` }
    }

    throw AnotherErrorYouCouldMake()
  } catch (error) {
    throw new Error(500, error)
  }
}

someFunction({...YourParams}, 'YourKey')
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!