typescript - 正确捕获打字稿捕获块中的对象
问题描述
我有一个可以将对象作为错误抛出的函数。我如何在打字稿中正确处理这个问题,因为被抛出的对象不是Error
例如:
function throwsSomeError() {
throw { code: 10, message: 'error' }
}
try {
throwsSomeError()
} catch (error: unknown) {
const message = error?.message;
// ^^ Object is of type 'unknown'.(2571)
}
解决方案
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
}
}
推荐阅读
- sonarqube - 不满足成功条件时,质量之门不会失败
- java - Java中String compareTo函数的时间复杂度是多少?
- javascript - Node.js 网络模块,从回调函数中获取数据
- javascript - 如何更改 Alpine.js 中的共享状态?
- python - 如何将谷歌地图 GeoJSON 转换为 GPX,保留位置名称
- php - 获取未定义索引:使用集合时出现饼干错误
- javascript - Vue中如何用子路由组件替换父视图
- python - 如何通过 Python 从 XML 中获取多个值?
- javascript - 重新实例化地图对象的问题 HERE 地图
- reactjs - 为使用 react 和 typescript 的方法添加哪些类型?