Javascript 向catch处理程序抛出错误,然后忽略函数?
我有一个助手函数:Javascript 向catch处理程序抛出错误,然后忽略函数?,javascript,promise,try-catch,Javascript,Promise,Try Catch,我有一个助手函数: function httpRequestHelper(body) { return fetch(`${host}:${port}`, { method: 'post', body: JSON.stringify(body) }) .then(function (response) { if (!response.ok) { throw Error(response.statusTe
function httpRequestHelper(body) {
return fetch(`${host}:${port}`, {
method: 'post',
body: JSON.stringify(body)
})
.then(function (response) {
if (!response.ok) {
throw Error(response.statusText);
}
return response.json();
})
.then(function(response) {
if (response.type === 'error') {
throw Error(response);
}
return response;
})
.catch(function(error) {
return error;
});
}
我写这篇文章是为了让各种命令的函数保持简短。这些函数只指定要发送的正文以及响应的哪一部分与使用者相关:
function hasActiveProject() {
return httpRequestHelper({ type: 'request', cmd: 'has_active_project' })
.then(function (response) {
return response.payload.value;
})
}
我执行如下各种命令:
try {
let hasActiveProjectResponse = await otii.hasActiveProject()
console.log(hasActiveProjectResponse);
} catch (error) {
console.log(error);
}
现在的问题是,在catch函数中,我希望得到抛出的错误消息,但相反,我得到的错误消息如下:
TypeError: Cannot read property 'value' of undefined
这是因为hasActiveProject()
尝试提取相关响应,即使出现错误,也会导致返回给catch(error)处理程序的不同错误
我怎样才能重写这个
保持精简hasActiveProject()
- catch处理程序接收原始错误
响应。有效负载是否未定义?因为在这个测试中,您可以看到它按您希望的方式工作,所以try会捕获.then函数中抛出的错误,并且不会继续
看起来response.type
是有效的,因此您没有抛出任何错误,您能确认您得到的结果吗
更新
经过进一步的研究,catch函数不会冒泡到下一个catch,它认为您已经处理了错误,并像往常一样继续(使用catch中解析的值)。
但您只需在.catch()中再次拒绝,这样您的错误就会冒泡到try/catch:
在httpRequestHelper()中
:
这会将您的错误发送到下一个捕获,请参见fiddle,例如:
谢谢!我玩弄了你的例子。httpRequestHelper中的catch方法似乎阻止了错误冒泡到try的外部catch部分。。。挡块。我不认为捕获方法捕获错误是有意义的!下面是使我意识到问题的修改后的代码:它在codepen上不起作用,但我无法在JSFIDLE上保存一段时间reason@user1283776如果答案正确,请接受。
.catch(function(error) {
return Promise.reject(error)
//return error;
});