【发布时间】:2019-06-11 17:48:04
【问题描述】:
在调用后端服务时使用 try-catch,因为它有可能返回空响应。
当响应为空时,标记错误:
“ReferenceError: modelInfo 未定义”。
API 可能已关闭并发生 ReferenceError 的事实是意料之中的。
为了处理这个错误,代码被包装在一个 try-catch 中。
我对 try-catch 的预期行为是它会在请求服务信息时出错,并跳转到“catch”,运行该代码。
catch 代码没有运行?
var activeMessage = view.querySelector('#activeMessage');
var html = '';
try {
//This call to the backend could throw a ReferenceError
ApiClient.getJSON(ApiClient.getUrl("VeraModelInfo")).then(function (modelInfo) {
html += modelInfo.Name;
html += '<br />';
html += modelInfo.InternalIp;
html += '<br />';
html += '<span id="icnConnectedContainer" style="color:rgb(82,181,75);font-size: 73%; opacity:0;">';
html += '<i class="md-icon" style="padding-bottom: 0.5%;">';
html += 'check_circle_outline';
html += '</i>';
html += ' Connected';
html += '</span > ';
activeMessage.style.opacity = 0;
activeMessage.innerHTML = html;
activeMessage.style.color = '#303030';
}
catch (error) { //This catch doesn't run after ReferenceError
html += '<span style="color: red" >';
html += '<i class="md-icon">';
html += 'circle_remove';
html += '</i>';
html += '<span>';
html += ' No Vera Home Automation Device Detected!';
activeMessage.innerHTML = html;
activeMessage.style.color = 'red';
activeMessage.style.opacity = 1;
activeMessage.style.display = 'block';
view.querySelector('#deviceModel').style.display = "none";
}
意识到错误并不总是异常...
当请求中有ReferenceError时如何抛出异常来运行catch代码。
或者识别ReferenceError来处理另一个函数中的客户端布局代码?
【问题讨论】:
-
.then()回调中的错误不能被catch子句捕获;这就是 Promise 机制的用途。
标签: javascript try-catch