TypeScript中AXIOS请求catch块error为unknown类型无法访问自定义消息如何解决
TypeScript catch块无法访问error.message的解决方案
TypeScript 4.4及以上版本默认将catch块捕获的错误标注为unknown类型,要求必须先完成类型收窄才能访问对应属性,避免运行时报错。你可以选择以下任意一种方案修复:
方案1:自定义错误类型守卫(最安全,适配自定义错误场景)
首先为你的自定义错误编写类型校验函数,在catch块中先校验错误类型再访问属性:
// 你的自定义错误定义示例 class CustomError extends Error { constructor(message: string) { super(message); this.name = "CustomError"; } } // 类型守卫函数,用于判断是否为你的自定义错误 function isCustomError(error: unknown): error is CustomError { return error instanceof CustomError; } // 业务代码修改 async activeAccount(uuid: string) { try { const response = await ApiClient( METHODS.GET, "Account/approveEmail", false, { uuid } ); } catch (error) { if (isCustomError(error)) { // 类型收窄后可正常访问message属性 this.showToastError(error.message); } else { // 非预期错误兜底逻辑 this.showToastError("系统发生未知错误"); } } }
方案2:通用Error类型校验(不需要区分自定义错误场景)
如果你不需要严格判断是不是你抛出的自定义错误,只要是标准Error实例就取message,可以简化类型守卫逻辑:
async activeAccount(uuid: string) { try { const response = await ApiClient( METHODS.GET, "Account/approveEmail", false, { uuid } ); } catch (error) { if (error instanceof Error) { this.showToastError(error.message); } else { // 非Error类型错误兜底,转成字符串展示 this.showToastError(String(error)); } } }
方案3:类型断言(仅适用于你100%确定错误类型的场景,不推荐)
如果你能确保该catch块捕获的一定是带message属性的错误,可以直接用类型断言跳过类型校验:
async activeAccount(uuid: string) { try { const response = await ApiClient( METHODS.GET, "Account/approveEmail", false, { uuid } ); } catch (error) { // 直接断言为你的自定义错误类型或者通用Error类型 this.showToastError((error as CustomError).message); } }
注意事项
- 不推荐直接将error断言为
any,会丢失所有类型校验能力,大幅提升运行时风险 - 生产环境优先选择类型守卫方案,兼顾类型安全和异常场景兜底
内容的提问来源于stack exchange,提问作者ZahraEsfandiary
相关产品推荐
相关产品推荐

