You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多API错误处理与页面展示:重复手机号场景需求优化

解决方案

核心修改内容

  • 新增页面错误状态变量,用于展示接口返回的具体错误信息
  • 优化请求逻辑,统一处理两个API的响应与错误
  • 针对手机号重复的400错误做精准捕获,更新页面错误提示
  • 提交前重置错误状态,保证重新提交时请求正常触发

修改后的完整代码

import { useState } from 'react';

// 初始化页面错误状态与加载状态(若未定义)
const [formError, setFormError] = useState('');
const [loading, setLoading] = useState(false);

const first = () => {
  // 提交前清空历史错误,开启加载状态
  setFormError('');
  setLoading(true);

  const registrationData = {
    first_name: values.first_name,
    last_name: values.last_name,
    gender: values.gender,
    dob: values.dob ? new Date(values.dob).toISOString() : null,
    email: values.email,
    phone_number: values.phone_number,
  };

  const locationData = {
    latitude: fetcedLocation?.latitude,
    longitude: fetcedLocation?.longitude,
    cur_status: "filled",
  };

  // 并行发起两个请求,确保都完成后处理结果
  Promise.all([
    requestInstance.post(API_ENDPOINT.LOCATION_REGISTRATION, locationData),
    requestInstance.post(API_ENDPOINT.EMPLOYEE_FIRST_REG, registrationData)
  ])
  .then(([locationRes, regRes]) => {
    console.log('位置信息提交状态:', locationRes.data.status);
    toast.success(regRes.data.message);
    // 无错误时跳转至下一页,根据实际路由框架调整跳转逻辑
    window.location.href = '/next-page'; // 或使用react-router的navigate等
    setLoading(false);
  })
  .catch((err) => {
    setLoading(false);
    // 捕获手机号重复的400错误
    if (err.response?.status === 400) {
      const errorMessage = err.response.data?.message || '手机号已存在,请更换后重试';
      setFormError(errorMessage);
      toast.error(errorMessage);
    } else {
      // 处理其他类型错误
      const errorMessage = err.response?.data?.message || '提交失败,请稍后重试';
      toast.error(errorMessage);
    }
  });
};

页面错误信息展示

在表单所在页面的合适位置添加错误提示区域:

{formError && (
  <div style={{ color: '#dc2626', margin: '1rem 0', fontSize: '0.9rem' }}>
    {formError}
  </div>
)}

关键逻辑说明

  • 请求协同:使用Promise.all并行处理两个API请求,确保只有当两个请求都成功时才执行跳转逻辑;若位置信息需先提交成功才能发起注册请求,可改为链式then调用实现串行请求
  • 错误精准处理:通过判断响应状态码400,提取接口返回的自定义错误信息,同时更新页面状态变量,让错误内容直接展示在页面上
  • 重新提交支持:每次提交前清空formError状态,避免旧错误干扰新提交,同时确保请求能正常触发

内容的提问来源于stack exchange,提问作者Sairam Gudiputi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 12:55:33