【问题标题】:Handle UnhandledPromiseRejectionWarning in a function calling another functions在调用另一个函数的函数中处理 UnhandledPromiseRejectionWarning
【发布时间】:2020-11-25 19:12:40
【问题描述】:

我在调用其他发出 axios 请求的函数的函数中处理 UnhandledPromiseRejectionWarning 时遇到问题。

const getCode = async () => {
  const code = await baseURL.get('/gcs/login/k?codigoCanal=4')
  return code
}

const posLogin = async (code) => {
  const poslogin = await baseURL.get(`/resource/autenticar/${code}`)
  return poslogin
}

const login = async () => {
 try {
  const code = await getCode();
  const finishedLogin = async posLogin(code)
 } catch (error) {
   handleLoginError(error)
 }
}

const handleLoginError = (error) => {
  if (error.response.status === 400) {
      throw new Error(`Bad Request; ${error.response.statusText}`)
    }
  if (error.response.status === 401) {
    throw new Error(`Wrong credentials; ${error.response.statusText}`)
  }
  throw new Error('Unknown Error')
}


login()

执行此代码返回 UnhandledPromiseRejectionWarning,但我意识到如果我在登录函数的 catch 中放置一个 try catch,此警告就会消失

} catch (error) {
  try {
    handleLoginError(error)
  } catch (err) {
    console.log('Ooppss', err)
  }

当我这样做时,我的代码进入嵌套的 catch 并且“err”值是 handleLoginError(error) 的值

如果不在 catch 中执行 try catch,我该如何做同样的事情?

【问题讨论】:

    标签: node.js error-handling axios


    【解决方案1】:

    看来你需要拨打login如下:

    try {
      await login();
    }
    catch(err) {
      // handle here the error
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-02
      • 2020-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-17
      相关资源
      最近更新 更多