React Query在全局onError处理程序中获取错误状态代码



创建queryClient时,我想创建一个全局onError处理程序,当错误响应代码为401时,该处理程序会刷新我的访问令牌。但我不知道如何访问onError处理程序中返回的错误的状态代码。

下面是我的全局onError处理程序,我只需要访问if语句中的响应代码就可以在适当的时候刷新我的令牌。

const queryClient = new QueryClient({
queryCache: new QueryCache({
onError: async (error, query) => {
// How to get status code fo error
if (error.status === 401) {
console.log("Refreshing Token");
await api.get("/api/refresh-token");
queryClient.refetchQueries(query.queryKey);
}
},
}),
});

您应该使用error.request.status来获得它。

const queryClient = new QueryClient({
queryCache: new QueryCache({
onError: async (error, query) => {
// How to get status code fo error
if (error.request.status === 401) {
console.log("Refreshing Token");
await api.get("/api/refresh-token");
queryClient.refetchQueries(query.queryKey);
}
},
}),
});

错误只是被拒绝的Promise所创建的,因此它取决于您如何进行实际的数据提取。

如果是axios,它很可能是AxiosError,所以状态代码应该在那里可用。

如果是fetch,那么这取决于如何将错误的状态代码转换为失败的Promise,因为fetch默认情况下不会这样做。如果只是:

if (!response.ok) {
throw new Error("no ok")
}

那么您根本没有关于状态代码的信息,因为您没有将其包含在错误中。

总而言之,这是react查询无法控制的,因为它不知道如何获取数据。

错误类型为"未知";,您需要映射此类型。我正在使用fetch来进行请求,并且可以将错误映射为"错误";响应";对象如果你需要查阅反错误的内容,可以用JSON.stringfy.打印

queryCache: new QueryCache({
onError: (error) => {
// JSON.stringify(error) if you are not secure and need to see the content, could print the error in strinfy
const response = error as Response
console.log('---------------------------------')
console.log(response.status) // 401
console.log(response.type) // default
console.log(response.ok) // false
console.log('---------------------------------')
}})

最新更新