Home > Software engineering >  How to handle UnhandledPromiseRejectionWarning
How to handle UnhandledPromiseRejectionWarning

Time:05-20

This bit of code, after connecting, does some stuff

controller.connect((response)=>{ does some stuff })

Down deep in the guts of the connect method this async function gets called, which returns a promise by way of the callback

async function ServerSend(endpoint,params,callback) {
      const response = axios.get(host endpoint, {params})
      callback(response);
} 

If the server is not available it correctly throws: UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED 127.0.0.1:8088

What is the correct way to handle this exception? I could possibly add a catch in the async method and rewrite all the call backs to return an err. But I'd rather catch it at the caller. I have not been able to get either method to work.

CodePudding user response:

axios.get(host endpoint, {params})  // this is a promise

so if it resolves it will be ok, but if it rejects (and yuou dont have any try .. catch, any .catch attached - it will throw error that exception is unhandled.

Why way would be to:

async function ServerSend(endpoint,params,callback) {
  try {
    const response = await axios.get(host endpoint, {params})
    callback(null, response);
  } catch (err) {
    callback(err, null);
  }
} 

OR

function ServerSend(endpoint,params,callback) {
  // most callbacks are two parameters - 1st erro or null, second data if no error is present.
  axios.get(host endpoint, {params}).then(data => callback(null, data)).catch(err => callback(err, null)); 
} 
  • Related