TypeScript中createAsyncThunk捕获错误时err类型为unknown的问题
解决createAsyncThunk中catch参数类型为unknown的TypeScript错误
问题场景
使用Redux Toolkit的createAsyncThunk发起接口请求时,当返回401状态码,通过throw new Error()抛出错误,但在catch块中访问err.message时,TypeScript提示错误:'err' is of type 'unknown'.ts(18046)。手动给catch参数标注Error类型也无法解决该问题。
原因分析
TypeScript规定catch语句的参数默认类型为unknown,因为运行时抛出的异常不一定是Error实例。直接给catch参数标注Error类型会被TypeScript忽略,因为无法保证运行时抛出的一定是Error对象。
解决方案
方法1:类型检查确认是Error实例
在catch块中先通过instanceof判断错误是否为Error实例,再访问message字段:
catch (err) { if (err instanceof Error) { return rejectWithValue(err.message); } // 处理非Error类型的异常 return rejectWithValue('未知错误'); }
方法2:类型断言(仅限确定抛出的是Error时使用)
如果能确保抛出的一定是Error实例,可以使用类型断言:
catch (err) { return rejectWithValue((err as Error).message); }
方法3:自定义错误类型(适用于更复杂的错误场景)
定义自定义错误类,抛出时使用该类,在catch中精准判断:
// 自定义Api错误类 class ApiError extends Error { constructor(message: string) { super(message); this.name = 'ApiError'; } } // 在createAsyncThunk中抛出 if (response.status === 401) { throw new ApiError("Invalid or missing jwtToken"); } // catch块中处理 catch (err) { if (err instanceof ApiError) { return rejectWithValue(err.message); } return rejectWithValue('未知错误'); }
修改后的完整代码示例
export const add = createAsyncThunk<any, Product, { state: RootState }>( 'product/addToCart', async (product, { getState, dispatch, rejectWithValue }) => { const response = await fetch(`${base_url}/main/wishlist/card`, { method: 'POST', body: JSON.stringify(product), headers: { Authorization: `Bearer ${getState().user.jwtToken}`, 'Content-Type': 'application/json' } }) try { if (response.ok) { const data = await response.json(); console.log("Successful addition of a product to the wishlist"); return data; } if (response.status === 400) { dispatch(refreshTokenRotation({})); dispatch(add(product)); } if (response.status === 401) { throw new Error("Invalid or missing jwtToken"); } } catch (err) { if (err instanceof Error) { return rejectWithValue(err.message); } return rejectWithValue('An unknown error occurred'); } } )
内容的提问来源于stack exchange,提问作者yonatan_
相关产品推荐
相关产品推荐

