TransWikia.com

Erro ao rejeitar promisse dentro de call back

Stack Overflow em Português Asked by le314u on February 18, 2021

Ao instanciar o seguinte Objeto

class Output {
    constructor(filePath) {
        this.stream = undefined
        this.nameFile = filePath
        this.fileOk = false
        this.file = this.createFile(this.nameFile)
        this.file.then().catch()
    }

    // Cria um arquivo para salvar o relatório de debug
    createFile(filePath) {
        let stream = ()=>{// Cria uma stream
            this.stream = fs.createWriteStream(filePath, {flags: 'a' })
        }
        return new Promise( (res, rej)=>{
            let nameFile = this.nameFile
            fs.open(filePath, "w", function(err) {
                if (err) { // Caso de erro
                    rej()
                } else {
                    res(stream())
                }
            })
        })
    }

Da o seguintes erros

(node:19531) UnhandledPromiseRejectionWarning: undefined

(node:19531) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:19531) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

como devo tratar o erro?

One Answer

Dessa forma você consegue facilmente tratar o erro que vem da sua função assíncrona de forma fácil usando o try catch.

exemplo:

class File {
  constructor(filePath) {
    this.file = filePath
  }

  create() {
    return new Promise((resolved, rejected) => {
      setTimeout(() => {
        const error = true;
        if (error) {
          rejected('Error');
        }
        
        resolved(this.file);
      }, 1000);
    });
  }
}

const file = new File('logo.png');

(async () => {
  try {
    const data = await file.create();
    console.log(data);
  } catch (error) {
    console.log(error);
  }
})();

dessa forma você consegue captar o erro que recebe da promise.

Answered by Luciano Alves on February 18, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP