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

React Query中如何设置并获取后端自定义错误信息

解决useMutation获取后端自定义错误信息的问题

你遇到的问题是因为axios抛出的错误对象里,默认message是通用的状态码提示,而后端自定义错误实际存在于error.response.data中。以下两种方法可以解决:

方法一:直接访问error的response.data

在组件中直接解构error后,通过response.data获取后端返回的自定义信息:

const {
    mutateAsync,
    isError: postStuffIsError,
    error 
} = postStuff();

// 替换成你后端返回的具体字段名,比如message/errMsg等
console.log(error?.response?.data?.message);

方法二:在自定义hook中维护错误状态

如果需要更清晰的错误管理,可以在postStuff hook里单独维护自定义错误状态,再返回给组件使用:

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

export const postStuff = () => {
    const [customError, setCustomError] = useState(null);
    
    const mutation = useMutation(
        async (token) =>
            await axios({
                url: foo,
                method: "post",
                data: { token },
            }),
        {
            onError: (error) => {
                setCustomError(error.response.data);
            },
            onSuccess: () => {
                setCustomError(null);
            }
        }
    );

    return { ...mutation, customError };
};

组件中使用:

const {
    mutateAsync,
    isError: postStuffIsError,
    customError 
} = postStuff();

// 直接获取自定义错误信息
console.log(customError?.message);

说明

axios请求失败时抛出的错误对象包含以下关键结构:

  • error.response:存在于请求已发送且后端返回响应(即使是4xx/5xx状态码)的情况
  • error.response.data:后端返回的完整响应体,里面就是你需要的自定义错误内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 20:10:41