Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

286
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda