【发布时间】:2021-03-18 23:30:13
【问题描述】:
我有一个 graphql 函数,它检查请求令牌是否已过期,如果已过期,我需要它重定向到登录。在我的应用程序的每个页面上,我都会调用服务器以获取一些数据,如果出现错误,我需要重定向到登录。我需要消除这里的代码重用,我需要一些帮助。
const client = new ApolloClient({
link: ApolloLink.from([
onError(({ graphQLErrors, operation, forward }) => {
if (graphQLErrors) {
graphQLErrors.forEach(err => {
// handle errors differently based on its error code
switch (err.extensions.code) {
case 'INTERNAL_SERVER_ERROR':
// This is the case when the user session expires
if (err.path && err.path[0] === 'updateToken') {
removeItem(AUTH_TOKEN);
history.push('/login');
}
return forward(operation);
default:
return forward(operation);
}
});
}
}),
]),
});
在我的应用程序的每个页面上,我都会向 graphql 客户端发出请求,
const Profiles = () => {
// Omitted code
const { loading, error, data, refetch, fetchMore } = useQuery(
GET_PROFILES(),
{
variables: { id },
}
);
if (loading) {
return <Loading />;
}
if (error) {
// I need to find a way to eliminate this line because I am duplicating it on every page of my app
if (error.message === '403: Forbidden' || error.message === '401: Unauthorized') {
return <Redirect to="/login" />;
}
return <Alert message="Error" description="Failed to load profiles." type="error" showIcon />;
}
return (
<div>OMITTED</div>
);
};
在我的应用程序的每个页面上,if 语句都有相同的错误。我需要删除检查错误消息的行,因为我在我的应用程序的每个页面上都复制了它。我在想也许我可以在 case 'INTERNAL_SERVER_ERROR': 案例上做点什么。
如果这些错误是真的,我不想显示警报
【问题讨论】:
-
失败时不转发? stackoverflow.com/a/63806405/6124657 ?