React项目中如何从400错误的API响应读取自定义错误信息
解决React中API 400错误的具体信息读取问题
核心思路
当API返回400错误时,HTTP请求库(如Axios)的错误对象会包含response字段,存储着服务器返回的完整错误数据。我们需要从该字段中逐层提取constraintViolations节点下的具体错误信息。
步骤1:修改API请求服务(serviceOsago.ts)
在请求函数的catch块中,解析错误响应的具体内容,替换通用错误提示:
假设原有请求代码如下:
import axios from 'axios'; export const submitOsagoData = async (data: any) => { try { const response = await axios.post('/api/osago/submit', data); return response.data; } catch (error) { throw new Error(`Request failed with status code ${(error as any).response.status}`); } };
修改为:
import axios from 'axios'; export const submitOsagoData = async (data: any) => { try { const response = await axios.post('/api/osago/submit', data); return response.data; } catch (error: any) { if (error.response && error.response.status === 400) { // 提取约束违规的具体错误信息 const errorDetails = error.response.data; // 取第一条错误信息,若需多条可拼接处理 const specificError = errorDetails.constraintViolations?.[0]?.message || 'Невідома помилка валідації'; throw new Error(specificError); } // 其他错误按原有逻辑处理 throw new Error(error.message || 'Запит не вдався'); } };
步骤2:在Reducer中处理错误(OfferReduces.ts)
在reducer的异步action中,捕获抛出的具体错误并更新状态:
示例代码:
import { submitOsagoData } from './serviceOsago'; // 定义action类型 const SUBMIT_OFFER_SUCCESS = 'SUBMIT_OFFER_SUCCESS'; const SUBMIT_OFFER_ERROR = 'SUBMIT_OFFER_ERROR'; export const submitOffer = (data: any) => async (dispatch: any) => { try { const result = await submitOsagoData(data); dispatch({ type: SUBMIT_OFFER_SUCCESS, payload: result }); } catch (error: any) { // 传递具体错误信息到状态 dispatch({ type: SUBMIT_OFFER_ERROR, payload: error.message }); } }; // 初始化状态 const initialState = { error: '', // 其他状态字段 }; // 处理状态更新的reducer export const offerReducer = (state = initialState, action: any) => { switch (action.type) { case SUBMIT_OFFER_ERROR: return { ...state, error: action.payload }; case SUBMIT_OFFER_SUCCESS: return { ...state, error: '' }; default: return state; } };
步骤3:在组件中展示错误
从Redux状态中读取错误信息,渲染到页面:
import { useSelector, useDispatch } from 'react-redux'; import { submitOffer } from './OfferReduces'; const OsagoForm = () => { const dispatch = useDispatch(); const error = useSelector((state: any) => state.offer.error); const handleSubmit = async (data: any) => { await dispatch(submitOffer(data)); }; return ( <div> {/* 表单内容 */} {error && <div className="error-message">{error}</div>} <button onClick={handleSubmit}>Відправити</button> </div> ); }; export default OsagoForm;
额外说明
- 若API返回多个
constraintViolations错误,可通过遍历拼接展示:errorDetails.constraintViolations.map(v => v.message).join('; ') - 加入空值判断避免因响应结构异常导致报错
- 若使用原生
fetch而非Axios,需先解析响应JSON再处理:
export const submitOsagoData = async (data: any) => { const response = await fetch('/api/osago/submit', { method: 'POST', body: JSON.stringify(data), headers: { 'Content-Type': 'application/json' } }); if (!response.ok) { const errorData = await response.json(); if (response.status === 400) { const specificError = errorData.constraintViolations?.[0]?.message || 'Невідома помилка'; throw new Error(specificError); } throw new Error(`Request failed with status code ${response.status}`); } return response.json(); };
内容的提问来源于stack exchange,提问作者Hunter91151
相关产品推荐
相关产品推荐

