js笔记--错误处理与调试

来源:互联网 发布:弹奏音乐的软件 编辑:程序博客网 时间:2024/05/23 12:35

 1.错误处理

try{}catch(error){}
与java一样,不同的是catch中必须给错误对象取名,即使不用该错误对象。包含一个共同属性message
finally子句:
无轮try,catch中包含什么代码(包括return)。最后都会执行finally中的代码。

2.错误处理策略

1.在比较时建议使用全等(===)和不全等(!==)
 ==和!=在比较不同类型时会先进行类型转换。可能出现类型转换错误
2.数据类型错误

检测参数类型

function getQueryString(url){if(typeof url == "string"){var pos = url.indexOf("?");if(pos>-1){return url.substring(pos+1);}}return "";}

function reverseSort(values){if(values instanceof Array){values.sort();values.reverse();}}
3.通信错误

ajax异步请求服务器时,URL或发送 的数据不正确。参数需使用encodeURIComponent()进行编码

function addQueryStringArg(url,name,value){if(url.indexOf("?") == -1){url += "?";}else{url += "&";}url += encodeURIComponent(name)+"="+encodeURIComponent(value);return url;}

4.对影响后续代码执行的错误进行异常捕获并处理,保证无关的业务代码模块可以正常运行不受影响

for(var i=0,len=mods.length;i<len;i++){try{mods[i].init(); //即使某个模块初始化出错,也不会影响其它模块的初始化}catch(ex){}}

3.调试技术

1.消息输出到控制台,console对象
  • error(message):错误消息 
  • info(message):信息性消息 
  • log(message):一般消息
  • warn(message):警告消息
2.消息记录到当前页面
在页面中开辟一小块区域,用来显示消息
function log(message){var console = document.getElementById("debuginfo");if(console === null){console = document.createElement("div");console.id = "debuginfo";console.style.background = "#dedede";console.style.border = "1px solid silver"; console.style.padding = "5px";console.style.width = "400px";console.style.position ="absolute"; console.style.right = "0px";console.style.top = "0px";document.body.appendChild(console);}console.innerHTML += "<p>"+message+"</p>";}

4.错误事件

任何没有通过try-catch处理的错误都会触发window对象的error事件。在任何Web浏览器中,onerror事件处理程序都不会创建event对象。但它可以接收三个参数:错误消息,错误所在的URL和行号。
要指定onerror事件,必须使用DOM0级技术。
window.onerror = function(message,url,line){console.log(message);return false;}throw new Error("呵呵,出错了!");
0 0
原创粉丝点击