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

251
Visualizações
Get rid of uncaught errors when resolving a promise

I have the following method

export abstract class BaseCalculator {
  /**
   * Compute the promise parameter.
   * @param name name of the parameter.
   * @param method promise to resolve.
   * @returns CalculatorResult.
   */
  public async computeParameter(name: string, method: Promise<string | number | boolean | ParamString>): Promise<CalculatorResult> {
    try {
      return Promise.resolve(method)
        .then(
          (computedValue: string | number | boolean | ParamString) =>
            this.getCalculatorResult(name, computedValue)
        )
        .catch((e: string | CalculatorError) => ({ // <<<<<<<<<<<<<<<<< HERE
          name: name,
          value: e instanceof CalculatorError ? e.value : NaN,
          error: e instanceof CalculatorError ? e : new CalculatorError(name, NaN, ErrorLevel.ERROR, e)
        } as CalculatorResult));
    }
    catch (e) { // <<<<<<<<<<<<<<<<< HERE
      return {
        name: name,
        value: e instanceof CalculatorError ? e.value : NaN,
        error: e instanceof CalculatorError ? e : new CalculatorError(name, NaN, ErrorLevel.ERROR, String(e))
      } as CalculatorResult;
    }
  }

I surround it with try/catch two times, one external, the second on promise.resolve, however I still get the uncatched errors when executing the methods passed as parameter to that computeParameter function.

enter image description here

could someone explain how to capture all the thrown errors when executing such async functions?

bellow is some code that ends to be called by one of the methods I pass in parameter

export function displayMessage(field: string, value: any, message: string, errorLevel: ErrorLevel): void {
  throw new CalculatorError(field, value, errorLevel, message)
}

export async function checkAngleSTR(
  STA: EnumSTA,
  KUNIT: number,
  STR: number,
  NEDSF: number,
  BFL: number,
  HFL: number,
  FCTM: number,
): Promise<void> {

  let ac: number = BFL * HFL;

  switch (STA) {
    case EnumSTA.EN1992_1_1_BS:
    case EnumSTA.EN1992_2_BS:
    case EnumSTA.EN_1992_3_BS:
      if (STR < 21.8 || STR > 45) {
        displayMessage("STR", NaN, "L'angle d'inclinaison de la bielle doit être compris entre 21.8° et 45°", ErrorLevel.ERROR);
      }
      break;
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You are using .then/.catch in a function tagged async (and never use await in that function) - this may be why errors slip between the cracks

So, either make computeParameter like this

(note, no async here, since await is never used)

computeParameter(name, method) {
    return method
        .then((computedValue) => this.getCalculatorResult(name, computedValue))
        .catch(e) => ({
            name,
            value: e instanceof CalculatorError ? e.value : NaN,
            error: e instanceof CalculatorError ? e : new CalculatorError(name, NaN, ErrorLevel.ERROR, e)
        }));
    }

or ... using async/await

async computeParameter(name, method) {
    try {
        const computedValue = await method;
        return this.getCalculatorResult(name, computedValue);
    } catch (e) {
        return {
            name,
            value: e instanceof CalculatorError ? e.value : NaN,
            error: e instanceof CalculatorError ? e : new CalculatorError(name, NaN, ErrorLevel.ERROR, e)
        };
    }
}

I've removed the "typescript" syntax to make the code clearer, and, as you say, typescript is irrelevant to the issue

Using either of these, the error thrown by displayMessage should now be correctly caught and handled

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