本文介绍了如何在JavaScript中捕获NetworkError?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Chrome的JavaScript控制台中,如果我运行它:
In Chrome's JavaScript console, if I run this:
var that = new XMLHttpRequest();
that.open('GET', 'http://this_is_a_bad_url.com', false);
that.send();
我收到故意预期的错误:
I get an intentionally expected error:
NetworkError: A network error occurred.
我想抓住这个,所以我使用:
I want to catch this, so I use:
var that = new XMLHttpRequest();
that.open('GET', 'http://this_is_a_bad_url.com', false);
try {
that.send();
} catch(exception) {
if(exception instanceof NetworkError) {
console.log('There was a network error.');
}
}
但是,我收到一条关于未定义NetworkError的错误:
However, I get an error about NetworkError not being defined:
ReferenceError: NetworkError is not defined
我怎样才能捕获NetworkError?
How can I catch NetworkError?
推荐答案
我认为你的意思是:
if(exception.name == 'NetworkError'){
console.log('There was a network error.');
}
我不相信错误是 NetworkError ,但是以这种方式抛出:
I don't believe the Error is an instance of NetworkError
, but thrown in this manner:
throw {
name: 'NetworkError',
message: 'A network error occurred.'
// etc...
}
这篇关于如何在JavaScript中捕获NetworkError?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!