Error while rejecting promise within call back

Asked

Viewed 105 times

0

By instantiating the following Object

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())
                }
            })
        })
    }

Give the following errors

(Ode:19531) Unhandledpromiserejectionwarning: Undefined

(Ode:19531) Unhandledpromiserejectionwarning: Unhandled Promise rejection. This error either originated 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) (Ode: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.

how should I treat error?

  • The best way to handle Promise errors is by using Try catch. , but there are other ways I wouldn’t recommend because you might face bigger problems later. is known as callback error is no longer so used.

1 answer

0

This way you can easily handle the error that comes from your asynchronous function easily using the Try catch.

example:

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);
  }
})();

this way you can capture the error you receive from the past.

  • in my case I’m calling the function inside the constructor and I can’t put await inside the constructor so I put await when I was instantiating surrounded by Try catch but it gave the following error (node:5706) UnhandledPromiseRejectionWarning: undefined

Browser other questions tagged

You are not signed in. Login or sign up in order to post.