获取承诺 - 返回500内部服务器错误 [英] fetch promises - return 500 internals server error
问题描述
我正在尝试在fetch中处理500个内部服务器错误。如果发生内部错误,服务器将响应消息。我想提取该消息。
I am trying to handle 500 internal server errors inside fetch. If an internal error occurs, the server responds with a message. I want to extract that message.
const req = new Request(url, {
method: node.method,
mode: 'cors',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
fetch(req)
.then((response) => {
if (response.status === 500) {
// res.json extracts the body from the response as a promise, chain
// .then on it and throw an error to be caught in the lower catch.
response.json()
.then((json) => {
const { message, stackTrace } = json;
throw new ServerException(message, stackTrace); // note 1
})
.catch((error) => {
return Promise.reject(RawException(error)); // note 2
});
} else {
return response.json();
}
})
.then((json) => { // note 3
dispatch(stopLoading());
dispatch(recieveResponse(typeOfRequest, json));
})
.catch((e) => {
dispatch(stopLoading());
dispatch(responseError());
dispatch(showError(e.message));
});
};
我的问题是提取响应的主体会产生新的承诺,我无法拒绝来自内部承诺的外部承诺。
My issue is that extracting the body of the response creates a new promise, and I am unable to reject the outer promise from the inner one.
注1触发内部承诺的catch方法。在内部捕获,我已经尝试抛出另一个错误但它似乎不起作用。如果我在第二个引用的行上抛出新的RawException(错误)
,则没有任何反应,并且在第三个注意到的然后
方法行触发器。如果我在提供的代码中返回被拒绝的承诺,那么仍然会触发但是json未定义。
Note 1 triggers the catch method of the inner promise. Inside catch, I have tried throwing another error but it doesn't seem to work. If I throw new RawException(error)
on the second noted line, nothing happens and the then
method on the third noted line triggers. If I return a rejected promise as I have in the code provided, then still triggers but json is undefined.
我该怎么做?
推荐答案
解决方案不是嵌套承诺,而是解决/返回外部的 .then
承诺结束内在的承诺。
The solution is not to nest promises, but to resolve/return the .then
of the outer promise with the conclusion of the inner promise.
if (response.status === 500) {
response.json() // response.json returns a promise, we chose to do nothing with its
.then((json) => { // conclusion
const { message, stackTrace } = json;
throw new ServerException(message, stackTrace); // note 1
})
.catch((error) => {
return Promise.reject(RawException(error)); // note 2
});
} else {
return response.json();
}
应该成为
if (response.status === 500) {
return response.json() // return the result of the inner promise, which is an error
.then((json) => {
const { message, stackTrace } = json;
throw new ServerException(message, stackTrace);
});
} else {
return response.json();
}
如果首选语法,也可以删除else子句。 ESLint抱怨其他人是浪费,但我更喜欢它使代码的分支明确。
The else clause can be removed as well if that syntax is preferred. ESLint complains about the else being wasteful, but I perfer the way it makes the code's branching explicit.
这篇关于获取承诺 - 返回500内部服务器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!