我想对从我进行的呼叫接收到的响应进行一些错误处理,然后如果命中特定的null检查,则移至catch。像这样:
fetch('example.json')
.then(response => {
if (response.data === null) {
//go to catch
}
})
.catch(error => {
console.error("error happened", error);
})
做这样的事情的最好方法是什么?在then块内引发错误的任何红旗吗?
答案 0 :(得分:0)
如果您throw
位于一个Promise处理程序中,则拒绝处理程序返回的Promise。所以:
fetch('example.json')
.then(response => {
if (response.data === null) {
throw new Error();
}
})
.catch(error => {
console.error("error happened", error);
})
您将抛出catch
处理程序看到的拒绝原因。 不必成为Error
,但与同步代码一样,通常最好是这样。
但是,请注意,A)A fetch
response
没有data
属性,B)您需要检查HTTP成功和解析返回的JSON。
您可能想要这样的东西:
fetch('example.json')
.then(response => {
if (!response.ok) {
// (I tend to use an specialized `Error` type here
// More on my anemic blog:
// http://blog.niftysnippets.org/2018/06/common-fetch-errors.html)
throw new Error("HTTP error " + response.status);
}
return response.json();
})
.then(data => {
if (data === null) {
throw new Error("The data is null");
})
// ...do something with `data`...
})
.catch(error => {
console.error("error happened", error);
});
在对您所说的问题的评论中:
我希望有一种方法可以检查此响应对象而不必触发抛出异常的“极端”措施
您有一个在结果上基本相同的替代方法:返回被拒绝的承诺。这是我上面适合进行此操作的第二个代码块:
fetch('example.json')
.then(response => {
if (!response.ok) {
// (I tend to use an specialized `Error` type here
// More on my anemic blog:
// http://blog.niftysnippets.org/2018/06/common-fetch-errors.html)
return Promise.reject(new Error("HTTP error " + response.status));
}
return response.json();
})
.then(data => {
if (data === null) {
return Promise.reject(new Error("The data is null"));
})
// ...do something with `data`...
})
.catch(error => {
console.error("error happened", error);
});
与throw
版本一样,您不必使用Error
,这只是最佳实践。可以是任何您想要的东西。
答案 1 :(得分:0)
如果需要,可以从您的Promise处理程序中抛出一个Error
对象。
fetch('example.json')
.then(response => {
if (response.data === null) {
throw new Error('oopsie');
}
})
.catch(error => {
console.error("error happened", error); // will show "Error: oopsie"
})