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
相关产品推荐
相关产品推荐

