fetch api 从服务器获取错误消息而不是通用消息

编程入门 行业动态 更新时间:2024-10-19 20:41:03
本文介绍了fetch api 从服务器获取错误消息而不是通用消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用 redux thunk 在一个动作中获取一些数据

I'm using redux thunk to fetch some data in an action

function handleErrors(response) { console.log(response) if (!response.ok) { throw Error(response.statusText); } return response; } export const something = (var) => dispatch => { fetch(`${url}/something`, {credentials: 'include'}) .then(handleErrors) .then(res => res.json()) .then(res => dispatch({ type: SOMETHING, payload: res }) ) .catch(error => dispatch({ type: ERROR, payload: error }) )

我的快递服务器出现错误时响应一些错误"

my express server on an error responds with 'some error'

return res.status(500).send({ message: 'some error' });

当它获取并且出现错误 (500) 时,它的消息是通用的内部服务器错误".

when it fetches and it's an error (500), its message is the generic "Internal Server Error".

我如何在 fetch 中得到一些错误"?

how do I get the 'some error' in fetch?

推荐答案

不确定您的 handleError 中有什么.提取错误消息的一种方法是这样的

Not sure what’s in your handleError. One approach to extract the error message would be something like this

fetch(url) .then(res => { // Check if response has errors if (res.ok) { // No errors return res.json(); } else { // Has errors, since res.json() returns a Promise, we // chain a then here to get the value and return the err value // as Promise rejection so that it will go to the // catch handler return res.json().then(err => Promise.reject(err)); // this could also be // return res.json().then(err => throw Error(err)); } }) .then(json => { // dispatch success }) .catch(err => { // dispatch error });

更多推荐

fetch api 从服务器获取错误消息而不是通用消息

本文发布于:2023-11-26 18:18:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634658.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:消息   而不是   错误   服务器   fetch

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!