[英]Error handling in Javascript promises(throwing errors)
我想对从我正在拨打的电话收到的响应进行一些错误处理,然后在特定的 null 检查被命中时转移到 catch。 像这样:
fetch('example.json')
.then(response => {
if (response.data === null) {
//go to catch
}
})
.catch(error => {
console.error("error happened", error);
})
关于做这样的事情,go 的最佳方式是什么? 在 then 块内抛出错误的任何危险信号?
如果您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) 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);
});
在对您所说的问题的评论中:
我希望有一种方法可以检查此响应 object 而不必触发抛出异常的“极端”措施
您确实有一个结果基本相同的替代方案:返回一个被拒绝的 promise。这是我上面的第二个代码块,用于执行此操作:
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
,这只是最佳实践。 它可以是任何你想要的。
如果需要,您可以从 promise 处理程序中抛出Error
object。
fetch('example.json')
.then(response => {
if (response.data === null) {
throw new Error('oopsie');
}
})
.catch(error => {
console.error("error happened", error); // will show "Error: oopsie"
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.