【问题标题】:Node - How to catch split() error?节点 - 如何捕获 split() 错误?
【发布时间】:2017-09-19 17:32:12
【问题描述】:

我有一个关于 NodeJ 的问题。从 6.6 开始,它表示无法获取未处理的承诺。

为了避免这种情况,我需要捕捉错误,但是......如果我得到了,我应该如何继续?

args[1] = args[1].split('!')[1].split('>')[0]

我尝试添加 .catch(err => console.log(err)) 但似乎没有任何改变。

提前致谢! :)

【问题讨论】:

  • 您发布的代码不是异步的,也没有返回承诺。
  • 你想更新你的代码sn-p
  • 代码中是否包含嵌套的Promises?
  • UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'catch' of undefined

标签: javascript node.js try-catch unhandled


【解决方案1】:

当第一次拆分没有产生第二个索引时,您可以通过替换字符串来避免错误。

args[1] = (args[1].split('!')[1] || "").split('>')[0];

这假设args[1] 肯定存在。如果不确定,您可以进行类似的替换。

args[1] = ((args[1] || "").split('!')[1] || "").split('>')[0];

最后,您可以提供一个默认值,以防其中任何部分未能产生有用的东西。

args[1] = ((args[1] || "").split('!')[1] || "").split('>')[0] || "DEFAULT";

【讨论】:

    【解决方案2】:

    .catch(err => console.log(err)) 用于从 Promise 中捕获错误。请改用标准格式:

    try{
        args[1] = args[1].split('!')[1].split('>')[0]
    }
    catch(err){
        console.log(err)
    }
    

    【讨论】:

      【解决方案3】:

      这或多或少是没有希望的。它只是一个简单的 javascript 语句,可以直接捕获如下: 尝试整体使用try catch

      try{
         args[1] = args[1].split('!')[1].split('>')[0]
      }catch(e){
      console.log(e); 
      // Most possible error would be TypeError: Cannot read property 'split' of undefined
      at <anonymous>:1:23
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-19
        • 2019-01-17
        • 2017-02-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多