react-hot-toast与GraphQL集成:错误处理与通知
react-hot-toast与GraphQL集成:错误处理与通知
在现代Web应用开发中,GraphQL已成为API交互的主流方案之一。然而,GraphQL错误处理往往比传统REST API更为复杂,需要专门的策略来确保用户体验。本文将介绍如何使用react-hot-toast与GraphQL集成,实现优雅的错误处理和用户通知系统。
1. 为什么需要专门的错误处理策略
GraphQL API通常返回一个包含"data"和"errors"字段的响应,即使请求成功执行也可能包含部分错误。这种特性使得错误处理变得更加复杂,需要前端应用能够智能地区分和处理不同类型的错误。
react-hot-toast提供了一个简单而强大的通知系统,通过src/core/toast.ts中的toast.promise方法,我们可以轻松地将GraphQL操作的生命周期与用户通知绑定起来。
2. 基础集成方案
以下是一个基本的GraphQL与react-hot-toast集成方案,使用toast.promise方法处理异步操作:
import { toast } from 'react-hot-toast';
import { useMutation } from '@apollo/client';
function AddToCartButton({ productId }) {
const [addToCart, { loading }] = useMutation(ADD_TO_CART_MUTATION);
const handleAddToCart = async () => {
return toast.promise(
addToCart({ variables: { productId } }),
{
loading: '添加中...',
success: '商品已加入购物车',
error: (err) => `添加失败: ${err.message}`
}
);
};
return <button onClick={handleAddToCart} disabled={loading}>
添加到购物车
</button>;
}
这个方案利用了src/core/toast.ts中定义的toast.promise方法,它会自动处理Promise的三种状态:loading、success和error,并显示相应的通知。
3. 高级错误处理
对于更复杂的GraphQL错误处理,我们需要解析GraphQL响应中的errors数组。react-hot-toast的toast.error方法可以配合自定义错误解析函数使用:
import { toast } from 'react-hot-toast';
import { useQuery } from '@apollo/client';
function ProductList() {
const { loading, error, data } = useQuery(PRODUCTS_QUERY);
React.useEffect(() => {
if (error) {
// 解析GraphQL错误
const errorMessages = error.graphQLErrors
.map(err => err.message)
.join('\n');
toast.error(errorMessages, {
duration: 10000, // 显示更长时间
style: {
border: '1px solid #ff4444',
padding: '16px',
color: '#ff4444',
},
});
}
}, [error]);
if (loading) return <div>Loading...</div>;
return (
<div>
{data.products.map(product => (
<ProductItem key={product.id} product={product} />
))}
</div>
);
}
4. 自定义通知组件
react-hot-toast允许我们创建自定义通知组件,以更好地展示GraphQL错误信息。通过src/components/toaster.tsx中的Toaster组件,我们可以自定义通知的外观和行为:
import { Toaster } from 'react-hot-toast';
function App() {
return (
<div>
{/* 应用内容 */}
<Toaster
position="top-right"
toastOptions={{
error: {
style: {
background: '#fff',
color: '#ff4444',
border: '1px solid #ff4444',
},
icon: <ErrorIcon />,
},
}}
/>
</div>
);
}
5. 错误分类与处理策略
GraphQL错误可以分为几类,每类需要不同的处理策略:
| 错误类型 | 处理策略 | react-hot-toast配置 |
|---|---|---|
| 验证错误 | 显示详细字段错误 | duration: 5000, style: { ... } |
| 权限错误 | 显示登录提示 | icon: , action: "登录" |
| 服务器错误 | 显示通用错误信息 | duration: 10000, style: { ... } |
| 网络错误 | 显示重试选项 | action: "重试", onClick: () => retry() |
通过使用src/core/use-toaster.ts提供的useToaster钩子,我们可以实现更精细的错误处理逻辑。
6. 完整示例:GraphQL查询错误处理
下面是一个完整的示例,展示如何处理GraphQL查询错误并使用react-hot-toast显示通知:
import { toast } from 'react-hot-toast';
import { useQuery } from '@apollo/client';
function UserProfile({ userId }) {
const { refetch } = useQuery(USER_PROFILE_QUERY, {
variables: { userId },
skip: !userId,
onError: (error) => {
// 解析GraphQL错误
const errors = error.graphQLErrors;
if (errors.some(e => e.extensions.code === 'PERMISSION_DENIED')) {
toast.error('您没有查看此用户资料的权限', {
action: {
label: '登录',
onClick: () => navigate('/login'),
},
});
} else if (errors.some(e => e.extensions.code === 'NOT_FOUND')) {
toast.error('用户不存在', {
duration: 3000,
});
} else {
toast.error('加载用户资料失败', {
action: {
label: '重试',
onClick: () => refetch(),
},
});
}
},
});
// 组件渲染...
}
7. 性能优化
当处理大量GraphQL操作时,我们需要注意通知系统的性能。react-hot-toast提供了几个优化选项:
- 使用toastId确保通知唯一性,避免重复显示相同错误
- 配置适当的duration,避免过多通知同时显示
- 使用toast.dismiss()和toast.removeAll()管理通知生命周期
通过合理配置这些选项,可以确保即使在复杂的GraphQL操作场景下,应用仍然保持良好的性能和用户体验。
8. 总结
react-hot-toast与GraphQL的集成提供了一个强大而灵活的错误处理和通知系统。通过使用本文介绍的方法,你可以为用户提供清晰、有用的错误信息,并帮助他们解决问题。无论是简单的操作反馈还是复杂的错误处理策略,react-hot-toast都能满足你的需求。
要了解更多关于react-hot-toast的信息,请参考官方文档和源代码:
更多推荐
所有评论(0)