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

121
Visualizações
How to add error handling to an async function call?

Currently the typescript code has this:

  React.useEffect(() => {
    if (prepAttrsRef.current) {
      prepAttrsRef.current.addEventListener('documentstatechanged', 
      async (evt: CustomEvent<FlowDocumentState>) => {
        if (evt.detail.draftState === 'all-changes-published') {
          dispatch(updateIsFlowpublished(true));
          let cleanSteps: readonly CleanStep[] = [];
          if (prepAttrsRef.current) {
            cleanSteps = await prepAttrsRef.current.getAllStepsOfTypeAsync('clean');
            if (cleanSteps && cleanSteps.length > 0 && cleanSteps[0] !== undefined) {
              await cleanSteps[0].selectAsync();
            }
          }
        }
      });
    }
    return () => {
      //TBC: cleanup
    };
  }, []);

Now we know that selectAsync() method returns a promise:

selectAsync(): Promise<SelectResponse>

And the SelectResponse could contain error message:

SelectResponse: { success: true } | { errorMessage: string; errorType: SelectError; success: false }

So in this case, how to add error handling code to await cleanSteps[0].selectAsync(); ? Should the await keyword to be removed here?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

So basically selectAsync method handles errors (those that are throw as and Error) and returns response object depending on success or failure.

You can get that response by

const response = await cleanSteps[0].selectAsync();

And check

const response = await cleanSteps[0].selectAsync();
if (response.success) {
   // Do some success handling
} else {
  // Do some error handling, you have { errorMessage: string; errorType: SelectError; success: false } object here
}

It really depends on what you want to do in each scenario.

If you want to know how to handle async function errors in general then you need to wrap content that might throw an error with try catch block

prepAttrsRef.current.addEventListener(
  'documentstatechanged',
  async (evt: CustomEvent<FlowDocumentState>) => {
    try {
      if (evt.detail.draftState === 'all-changes-published') {
        dispatch(updateIsFlowpublished(true));
        let cleanSteps: readonly CleanStep[] = [];
        if (prepAttrsRef.current) {
          cleanSteps = await prepAttrsRef.current.getAllStepsOfTypeAsync(
            'clean'
          );
          if (
            cleanSteps &&
            cleanSteps.length > 0 &&
            cleanSteps[0] !== undefined
          ) {
            await cleanSteps[0].selectAsync();
          }
        }
      }
    } catch (error) {
      // Do some error handling
    }
  }
);

Promise chain in async/await

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