我使用带有Redux的fetch API和thunk中间件,我认为处理网络错误的方式有点奇怪。这是一个简单的异步操作:
const fetchData = (id) => (dispatch) => {
dispatch(requestData())
return fetch(`/my/api/${ id }`)
.then(response => response.json())
.then(json => dispatch(receiveDataSuccess(json, id)))
.catch(err => dispatch(receiveDataFail(err, id)))
}
但如果出现404或500状态的网络错误,则会转换为SyntaxError: Unexpected end of JSON input
等JSON解析错误。为了解决这个问题,我将我的行动改为:
const fetchData = (id) => (dispatch) => {
dispatch(requestData())
return fetch(`/my/api/${ id }`)
.then(response => {
switch (response.status) {
case 200:
return response.json()
default:
// Here I just throw an error for it
// to be catched by the promise chain
throw {
status: response.status
}
}
})
.then(json => dispatch(receiveDataSuccess(json, id)))
.catch(err => dispatch(receiveDataFail(err, id)))
}
通过这种方式,我可以向用户显示更有意义的错误消息,而不仅仅是"出现错误" 。
这是处理此问题的正确方法还是我错过了什么?