可以在打字稿中捕获打字稿错误
我无法捕获错误。我故意把查询字符串弄乱了以处理此情况,但仍然可以通过。使用开发人员工具打开,应用程序崩溃。我正在使用Axios,Redux-Toolkit和Typescript。请告诉我我该怎么办?
export const fetchUsers = createAsyncThunk(
'user/fetchAll',
async (_, {rejectWithValue}) => {
try {
const response = await axios.get<IUser[]>('https://jsonplaceholder.typicode.com/use2rs')
return response.data
} catch (e) {
if (e instanceof Error) {
return rejectWithValue(e.message)
}
}
}
)
但是,当我使用这样的工具时,一切都很好。但是,我想利用createasyncthunk和recultwithvalue的便利性
export const fetchUsers = () => async (dispatch: AppDispatch) => {
try {
dispatch(userSlice.actions.usersFetching())
const response = await axios.get<IUser[]>('https://jsonplaceholder.typicode.com/users')
dispatch(userSlice.actions.usersFetchingSuccess(response.data))
} catch (e: any) {
dispatch(userSlice.actions.usersFetchingError(e.message))
}
}
I can't catch the error. I deliberately messed up the query string to handle this case, but it still gets through. With developer tools open, the app crashes. I am using axios, redux-toolkit and typescript. Please tell me what should I do?
export const fetchUsers = createAsyncThunk(
'user/fetchAll',
async (_, {rejectWithValue}) => {
try {
const response = await axios.get<IUser[]>('https://jsonplaceholder.typicode.com/use2rs')
return response.data
} catch (e) {
if (e instanceof Error) {
return rejectWithValue(e.message)
}
}
}
)
But when I use such a tool, everything works well. However, I'd like to use the convenience of createAsyncThunk and rejectWithValue
export const fetchUsers = () => async (dispatch: AppDispatch) => {
try {
dispatch(userSlice.actions.usersFetching())
const response = await axios.get<IUser[]>('https://jsonplaceholder.typicode.com/users')
dispatch(userSlice.actions.usersFetchingSuccess(response.data))
} catch (e: any) {
dispatch(userSlice.actions.usersFetchingError(e.message))
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Instance Orror
几乎永远无法使用,因为扩展
JavaScript内部类,例如错误>错误
可能会导致从技术上不保留正确的属性链的类。这可能取决于您的转卸目标。最好检查
typeof error.message =='string'
之类的东西,或者写下一些类型级:instanceof Error
almost never works, sinceextending
JavaScript-internal classes likeError
can result in classes that technically do not keep the right property chain. This might differ depending on your transpilation target.Better check something like
typeof error.message == 'string'
or write a little typeguard: