Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to check for javascript syntax errors

2025-04-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

这篇文章主要介绍"怎么检查javascript语法错误"的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇"怎么检查javascript语法错误"文章能帮助大家解决问题。

在javascript中可以使用"_window.onerror"来检查语法错误,还可以捕捉运行时错误,代码如"_window.onerror = function(msg,url,line,col,error){...}"。

本文操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。

怎么检查javascript语法错误?

JavaScript中错误检查方法:

try-catch 存在的局限(此方法可在javascript如何进行错误处理?中查看)

无法捕捉到语法错误(因为代码完全没运行..)

需要借助工具把所有的function块以及文件块加入try,catch

使用_window.onerror

可以捕捉语法错误,也可以捕捉运行时错误;

可以拿到出错的信息,堆栈,出错的文件、行号、列号;

只要在当前页面执行的js脚本出错都会捕捉到,例如:浏览器插件的javascript、或者flash抛出的异常等。

跨域的资源需要特殊头部支持。

常见的错误处理程序如下:

_window.onerror = function(msg,url,line,col,error){ //没有URL不上报!上报也不知道错误 if (msg != "Script error." && !url){ return true; } //采用异步的方式 //我遇到过在_window.onunload进行ajax的堵塞上报 //由于客户端强制关闭webview导致这次堵塞上报有Network Error //我猜测这里_window.onerror的执行流在关闭前是必然执行的 //而离开文章之后的上报对于业务来说是可丢失的 //所以我把这里的执行流放到异步事件去执行 //脚本的异常数降低了10倍 setTimeout(function(){ var data = {}; //不一定所有浏览器都支持col参数 col = col || (window.event && window.event.errorCharacter) || 0; data.url = url; data.line = line; data.col = col; if (!!error && !!error.stack){ //如果浏览器有堆栈信息 //直接使用 data.msg = error.stack.toString(); }else if (!!arguments.callee){ //尝试通过callee拿堆栈信息 var ext = []; var f = arguments.callee.caller, c = 3; //这里只拿三层堆栈信息 while (f && (--c>0)) { ext.push(f.toString()); if (f === f.caller) { break;//如果有环 } f = f.caller; } ext = ext.join(","); data.msg = ext; } //把data上报到后台! },0); return true;//返回true是因为不需要在console中打印错误了};关于"怎么检查javascript语法错误"的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注行业资讯频道,小编每天都会为大家更新不同的知识点。

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report