【问题标题】:type script : type of error in catch closuretypescript : catch 闭包中的错误类型
【发布时间】:2021-12-26 04:40:14
【问题描述】:

我正在使用 typescriptVueJS

我这里有输入错误

如你所见,我做了type assertation

错误继续

catch (err) {
  
   const  msg = (err as TypeError)?.response?.statusText
}

我应该做什么

【问题讨论】:

  • 不应该是catch (err: TypeError)吗?
  • @bassxzero 打字稿不支持。 catch 块中的错误只能是unknownany
  • @bassxzero ,那么我们将在响应时出现类型错误:err.response

标签: typescript vue.js nuxt.js


【解决方案1】:

要解决您的问题,您可以检查err 是否真的是TypeError,例如:

catch (err) {

   if (err instanceof TypeError) {
  
       const  msg = err.response?.statusText

   }
   
}

更多信息: err 可以是任何东西,因为你可以在 javascript 中抛出任何你喜欢的东西(你可能应该避免):

function foo() {
    try {
        throw 'this is not an error'; // don't do that!
    } catch (err) {

        if (err instanceof Error) {
            console.error('error', err);
        } else {
            console.log('log', err);
        }
    }
}

foo(); // log this is not an error

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-20
    • 2022-11-25
    • 2021-06-28
    • 1970-01-01
    • 2015-08-24
    • 1970-01-01
    • 2018-10-13
    相关资源
    最近更新 更多