【发布时间】:2020-10-12 23:56:02
【问题描述】:
我有一个 React/Redux 操作创建者,它在创建新用户帐户时发出发布请求。
当我测试服务器验证时,我期望在 catch 中定义 err.response 对象并返回验证错误消息。但是,err.response 和 err.request 对象未定义,当用户应该看到验证错误时,我得到了通用的“发生内部错误”。
我已经按照他们在https://github.com/axios/axios#handling-errors 推荐的设置进行了操作,但是我发现没有运气。有什么想法吗?
import { REGISTER_SUCCESS, REGISTER_FAILED, RegisterReq, TokenRes } from "./types";
import { returnErrors } from "../errors/actions";
import { Config } from "../../utils/tokenConfig";
import axios, { AxiosResponse, AxiosError } from "axios";
export const registerUser = (user: RegisterReq) => (dispatch:Function):void => {
const config: Config = {
headers: {
"Content-Type": "application/json"
},
withCredentials: false
};
axios.post<TokenRes>("/v1/users", user, config)
.then((res: AxiosResponse<TokenRes>):void => dispatch({
type: REGISTER_SUCCESS,
payload: res.data
}))
.catch((err: AxiosError):void => {
if(err.response) dispatch(returnErrors(err.response.data, err.response.status, REGISTER_FAILED));
else if(err.request) dispatch(returnErrors(err.request.data, err.request.status, REGISTER_FAILED));
dispatch(returnErrors("An internal error occurred", 500, REGISTER_FAILED));
});
};
【问题讨论】:
-
err.message()的值是多少? -
“请求失败,状态码为 400”,这是我定义服务器在输入无效时返回的状态码
-
如果发生错误,您将从服务器创建什么样的响应对象。正如我在询问错误 DTO?
-
什么是
console.log(err)。我认为这是因为您需要在端点中定义它 -
@Mohit 我正在使用 express-validator 它返回
res.status(400).json(err.message)其中err.message只是一个字符串
标签: reactjs typescript redux axios