微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用TypeScript 2.9创建扩展初始错误的新异常?

如何解决如何使用TypeScript 2.9创建扩展初始错误的新异常?

我写了一个函数来用TypeScript级联React和React Native中的错误

/**
 * Function that takes an error and trow an enriched error
 * @param error the original error
 * @param func the name of the function trowing the error
 * @param params the parameters passer to the function
 * @param custom a custom message to add*
 * @returns an enriched error
 */
const throwR = (error: Error,func?: string,params?: any,custom?: string) => {
  // Parse params in an human readable form
  let parsedParams: string = ''
  if (params && typeof params === 'object') {
    try {
      parsedParams = JSON.stringify(params)
    } catch (err) {
      parsedParams = `${params.toString()} (JSON.stringify returned: ${err})`
    }
  } else {
    try {
      parsedParams = params.toString()
    } catch (err) {
      parsedParams = `<params.toString(): ${err}>`
    }
  }

  // Handle the case where no error message is provided
  if (!error) {
    try {
      console.log(`on ${func}(${parsedParams})${' ' + custom}: No error message provided to throwR`)
    } catch (err) {
      console.log(`No error message provided to throwR and unable to build this message: ${err}`)
    }
  }

  // build the error message
  let message: string = ''
  try {
    message = `on ${func}(${parsedParams})${' ' + custom}: ${error}`
  } catch (err) {
    message = `${error} (Could not build enriched message: ${err})`
  }

  // build the new error
  const newError = new Error(message)

  // add the original error name
  try {
    newError.name = error.name
  } catch (err) {
    console.log(`on throwR,Could not add a name to the error: ${error}`)
  }

  // by the end,throw the error
  throw newError
}

export default throwR

然后我将其用于:

const myFunction(params) => {
  try {
    // potentially faulty code
  } catch (error) {
    throwR(error,'myFunction',params,'custom message')
  }
}

我去了论坛,然后看到大多数人都在使用自定义错误类:

const myFunction(params) => {
  try {
    // potentially faulty code
  } catch (error) {
    throw new CustomError(error,customParameter)
  }
}

我是一个初学者,还不太了解每种方法的含义。我想避免一个大的陷阱,该陷阱以后意味着我需要重构所有代码

您能否解释一下每种方法的含义,并为我提供针对自定义错误和级联错误的正确方法

谢谢

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?