使用 Tanstack Query 和 Axios 的优雅错误处理(最佳组合??)

发布: (2025年12月12日 GMT+8 04:44)
4 min read
原文: Dev.to

Source: Dev.to

后端服务

我们为该项目采用了非常简单的架构。

  • Supabase 作为 BaaS 处理身份验证、会话管理等。
  • Express 处理授权、数据库查询以及其他后端服务。

对于 Express,我们使用了简化的 MVC 架构:

  • Models – 负责使用 Supabase 的所有数据库操作。
  • Views – 前端的服务类。
  • Controllers – 包含业务逻辑。

我们仅使用这些名称来确保结构和关注点分离。

示例 Controller

export const completeProfile = async (req, res) => {
  try {
    const { role, userData } = req.body;

    const existingProfile = await UserProfileModel.getCustomerProfile(req.user.id);

    if (existingProfile) {
      return res.status(400).json({
        error: "ProfileError",
        message: "Profile already exists",
      });
    }

    const result = await UserProfileModel.createProfileWithEntity(
      req.user.id,
      role,
      userData
    );

    res.json({
      message: "Profile completed successfully",
      role,
      userId: req.user.id,
    });
  } catch (error) {
    res.status(500).json({
      error: "ProfileError",
      message: error.message,
    });
  }
};

当用户尝试创建已存在的个人资料时,controller 会返回 400 响应:

{
  "error": "ProfileError",
  "message": "Profile already exists"
}

好的部分:Axios

Axios 是基于 Promise 的 HTTP 客户端,相比原生 fetch API 简化了 API 请求。

使用 fetch

const completeProfile = async (payload) => {
  const res = await fetch('/profile/complete', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload),
  });

  if (!res.ok) {
    const errorData = await res.json().catch(() => ({}));
    throw new Error(errorData.message || 'Failed to complete profile');
  }

  return res.json();
};

使用 Axios

import axios from 'axios';

const completeProfile = async (payload) => {
  const { data } = await axios.post('/profile/complete', payload);
  return data;
};

Axios 错误对象

当响应状态不在 2xx 范围内时,Axios 会抛出如下错误对象:

{
  "response": {
    "status": 400,
    "data": {
      "error": "ProfileError",
      "message": "Profile already exists"
    }
  }
}

这消除了手动 if (!res.ok) 检查的需求。

TanStack Query(前身为 React Query)

与其在每个组件中使用 try / catch 处理错误,TanStack Query 将数据获取、缓存、加载状态和错误处理集中管理。

什么是 TanStack Query?

TanStack Query 是一个强大的 React 数据获取和状态管理库。它会自动管理:

  • 加载状态
  • 错误处理
  • 重试与缓存
  • 后台重新获取

这让你可以专注于构建功能,而不是编写样板代码。

使用 TanStack Query 与 Axios

import { useMutation } from '@tanstack/react-query';

const useCompleteProfile = () => {
  return useMutation({
    mutationFn: (payload) => completeProfile(payload),
  });
};

在组件中处理错误

import { View, Text } from 'react-native';
import { useCompleteProfile } from './hooks';

const CompleteProfileComponent = ({ payload }) => {
  const mutation = useCompleteProfile();

  const handleSubmit = () => {
    mutation.mutate(payload);
  };

  return (
    <View>
      {/* ...your form UI... */}

      {mutation.isError && (
        <Text>
          {mutation.error?.response?.data?.message || 'An error occurred'}
        </Text>
      )}
    </View>
  );
};

当 Axios 抛出错误时,mutation.isError 标志会自动变为 true,错误详情可以通过 mutation.error 访问。

图片

后端架构

项目概览

Axios vs Fetch

Back to Blog

相关文章

阅读更多 »

内部实现:React

介绍 我自从开始使用 React 的那一刻起就想做这件事:了解它的运行机制。这不是对源代码的细粒度审查。在…

React 使用计算器

今天我完成了一个使用 React 的练习项目——计算器。这个 React Calculator 应用程序执行基本的算术运算。它支持按钮…