简体   繁体   中英

nodejs how to handle a function's error in trycatch

I have a method that I want place inside a try catch. How would I change the syntax so it handles it correctly in a trycatch?

try{
    rekognition.detectFaces(params, function(err, data) {

    });
}catch(e){

}

Getting the error: error expected to be handled

This is probably an asynchronous function call -

rekognition.detectFaces(params, function(err, data) {
  // ...
})

You cannot wrap such a call with try / catch . Instead the convention is to handle errors in the callback -

rekognition.detectFaces(params, function(err, data) {
  // handle errors here...
  if (err) {
    // do something
    console.error(err)
  }
  else {
    // no errors here
    console.log(data)
  }
})

A better option is to use util.promisify -

const { promisify } =
  require("util")

const detectFaces =
  promisify(rekognition.detectFaces.bind(rekognition))

detectFaces(params)
  .then(result => console.log("got result", result))
  .catch(err => console.error("error encountered", err))

Such promisify function simply converts a callback-style function to Promise-based async function. It's a generic transformation -

const promisify = func =>
  (...args) =>
    new Promise
      ( (resolve, reject) =>
          func
            ( ...args
            , (err, result) =>
                err
                  ? reject(err)
                  : resolve(result)
            )
      )

Using the Promised-based function, try / catch is possible if we also use async / await -

const detectFaces =
  promisify(rekognition.detectFaces.bind(rekognition))

async function main () {        // <-- async
  try {                         // <-- try
    const result =
      await detectFaces(params) // <-- await

    console.log(result)
  }
  catch (err) {                 // <-- catch
    console.error(err)
  }
}

main()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM