首页 > 解决方案 > 正确捕获打字稿捕获块中的对象

问题描述

我有一个可以将对象作为错误抛出的函数。我如何在打字稿中正确处理这个问题,因为被抛出的对象不是Error

例如:

function throwsSomeError() {
  throw { code: 10, message: 'error' }
}

try {
  throwsSomeError()
} catch (error: unknown) {
  const message = error?.message;
  //              ^^ Object is of type 'unknown'.(2571)
}

ts游乐场

标签: typescript

解决方案


https://fettblog.eu/typescript-typing-catch-clauses/

您不必在 catch 参数括号中指定类型,然后您检查错误是 catch 范围内的数据类型。

try {
  throwsSomeError()
} catch (error) {
  if (error instanceof Error) {
    const message = error?.message;
  } else {
    // everything else
  }
}

编辑:

建议创建自定义错误类,以便判断错误对象的类型。

class CustomError extends Error {
    code?: number
    constructor(code?: number, message?: string) {
        super(message);
        this.code = code
    }
}


function throwsSomeError() {
  throw new CustomError(10, 'error')
}

try {
  throwsSomeError()
} catch (error) {
  if (error instanceof CustomError) {
    const message = error?.message;
  } else {
    // everything else
  }
}

推荐阅读