【发布时间】:2016-09-01 20:55:04
【问题描述】:
我正在使用同构 fetch 发出 API 请求,并使用 Redux 来处理我的应用程序的状态。
我想通过触发 Redux 操作来处理互联网连接丢失错误和 API 错误。
我有以下(正在进行的/错误的)代码,但无法找出触发 Redux 操作的正确方法(而不是仅仅抛出错误并停止一切):
export function createPost(data = {}) {
return dispatch => {
dispatch(requestCreatePost(data))
return fetch(API_URL + data.type, {
credentials: 'same-origin',
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-WP-Nonce': API.nonce
},
body: JSON.stringify(Object.assign({}, data, {status: 'publish'}))
}).catch((err) => {
//HANDLE WHEN HTTP ISN'T EVEN WORKING
return dispatch => Promise.all([
dispatch({type: PRE_FETCH_RESOURCES_FAIL, errorType: 'fatal', message:'Error fetching resources', id: h.uniqueId()}),
dispatch({type: PRE_CREATE_API_ENTITY_ERROR, errorType: 'fatal', id: h.uniqueId(), message: 'Entity error before creating'})
])
}).then((req) => {
//HANDLE RESPONSES THAT CONSTITUTE AN ERROR (VIA THEIR HTTP STATUS CODE)
console.log(req);
if (!req || req.status >= 400) {
return dispatch => Promise.all([
dispatch({type: FETCH_RESOURCES_FAIL, errorType: 'warning', message:'Error after fetching resources', id: h.uniqueId()}),
dispatch({type: CREATE_API_ENTITY_ERROR, errorType: 'warning', id: h.uniqueId(), message: 'Entity error whilst creating'})
])
}
else {
return req.json()
}
}).then((json) => {
var returnData = Object.assign({},json,{
type: data.type
});
dispatch(receiveCreatePost(returnData))
})
}
}
如果我在 JS 控制台中故意禁用互联网连接,当我通过 console.log() 登录时(如上),它会输出以下内容:
POST http://example.com/post net::ERR_INTERNET_DISCONNECTED(anonymous function)
(dispatch) {
return Promise.all([dispatch({ type: PRE_FETCH_RESOURCES_FAIL, errorType: 'fatal', message: 'Error fetching resources', id: _CBUtils2.default.uniqueId() }), dispatch({ type:…
cb_app_scripts.js?ver=1.0.0:27976 Uncaught (in promise) TypeError: req.json is not a function(…)
如果这是完全错误的,请原谅我,但我不想做任何事情,只是在出现错误时触发两个 Redux Actions(一个一般错误,一个特定于我们在错误发生时执行的操作) .
我正在努力实现的目标是否可能?
似乎(通过我的控制台日志记录)脚本的“then”部分仍在执行(因为它的内容是我的“catch”调度函数)..
【问题讨论】:
标签: javascript fetch redux