Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

285
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda