gpt4 book ai didi

javascript - 如何将Axios错误返回给客户端? (不仅记录)

转载 作者:行者123 更新时间:2023-12-03 08:36:45 24 4
gpt4 key购买 nike

我知道这个问题已经被问过很多次了,但是我面临的是一个非常烦人的问题。
我的服务器返回状态代码为500的错误字符串。当我使用axios并捕获错误时,我可以轻松地记录它,但是当我返回它时,我可以尝试所有操作,但是它给了我未定义的内容,或者没有附加内容任何东西。

export const submitCheckout = async (betImport, ticket_id, token) => {
const res = await axios({
method: "post",
url: rootUrl + "bets/checkout/" + ticket_id,
headers: {
"x-auth-token": token,
},
data: {
betImport,
},
}).catch(({ response }) => {
console.log(response.status) //this works
return response;
});
return res.data;
};

//HERE I CALL THE FUNCTION

const res = await submitCheckout(sum, ticket_id, token);
//here i can access only the body of the error, even if i try to append something to it.
if (res.ticket_id) {
emptyTicket();
setmodal({
show: true,
title: "SUCCESS",
subtitle: "BET PLACED",
maxwin: `${res.maxWin}`,
ticketId: `${res.ticket_id}`,
account_sum: `${res.account_sum}`,
});
ModifyAccountUser(user, res.account_sum);
} else {
setmodal({
title: "ERROR",
show: true,
status: `${res.status}`,
error: `${res}`,
});
if (res.toString().includes("Token")) history.push("/login");
}

//WHAT I WANT TO DO
export const submitCheckout = async (betImport, ticket_id, token) => {
const res = await axios({
method: "post",
url: rootUrl + "bets/checkout/" + ticket_id,
headers: {
"x-auth-token": token,
},
data: {
betImport,
},
}).catch(({ response }) => {
return {...response, response.status}; //this returns the body only,
return {res: response, status: response.status}; //this crashes,
return response + "-"+ response.status}; //this was my desperation attack and failed as well
});
return res.data;
};

最佳答案

引发错误,并将您的响应作为字符串放入其中。然后按照您的 promise 通过error.message访问它:

async function foo(){
try{
const res = await ax.post("url", {params})
return res
}
catch(err){
throw new Error("my error message")
}
}

//then

foo()
.then(res=> do stuff)
.catch(err=> err.message)

关于javascript - 如何将Axios错误返回给客户端? (不仅记录),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65858311/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com