Syn*_*ead 16 javascript xmlhttprequest referenceerror
在Chrome的JavaScript控制台中,如果我运行它:
var that = new XMLHttpRequest();
that.open('GET', 'http://this_is_a_bad_url.com', false);
that.send();
Run Code Online (Sandbox Code Playgroud)
我得到了一个故意预期的错误:
NetworkError: A network error occurred.
Run Code Online (Sandbox Code Playgroud)
我想抓住这个,所以我使用:
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.');
}
}
Run Code Online (Sandbox Code Playgroud)
但是,我收到一个关于未定义NetworkError的错误:
ReferenceError: NetworkError is not defined
Run Code Online (Sandbox Code Playgroud)
我怎样才能捕获NetworkError?
Rob*_* M. 15
我想你的意思是:
if(exception.name == 'NetworkError'){
console.log('There was a network error.');
}
Run Code Online (Sandbox Code Playgroud)
我不相信Error是一个实例NetworkError,但是以这种方式抛出:
throw {
name: 'NetworkError',
message: 'A network error occurred.'
// etc...
}
Run Code Online (Sandbox Code Playgroud)
我在寻找一种方法来检查Network Error我在使用 Axios 时得到的答案时找到了这个答案,所以如果您不使用 Axios,这个答案可能不适合您。
我通过 Axios 收到的错误对象具有config和属性,并且 和request都具有属性。对象的属性如下图所示:responserequestresponsestatusresponse
我的 axios 配置如下所示:
\n\nthis.client = axios.create(options);\nthis.client.interceptors.response.use(this.handleSuccessResponse, this.handleErrorResponse);\nthis.unauthorizedCallback = () => {};\nRun Code Online (Sandbox Code Playgroud)\n\n方法handleErrorResponse是:
handleErrorResponse(error) {\n // use the information from the error object here\n}\nRun Code Online (Sandbox Code Playgroud)\n\n编辑:按照@Erd\xc5\x91s-Bacon的建议:
\n\n如果您使用 axios 和 nginx,这可能是给您的评论。我遇到了问题error.response,undefined结果发现这是因为 CORS 问题。必须将我的 nginx 配置设置为关键字“始终添加适当的标头”来解决 CORS,否则标头会在错误响应时被删除,从而出现 CORS 问题。请参阅此答案以获取更多信息。