Home>Article>Web Front-end> How to check javascript syntax errors

How to check javascript syntax errors

藏色散人
藏色散人 Original
2021-07-02 11:40:04 3113browse

You can use "window.onerror" in javascript to check syntax errors and capture runtime errors. Code such as "window.onerror = function(msg,url,line,col,error){.. .}".

How to check javascript syntax errors

The operating environment of this article: windows7 system, javascript version 1.8.5, Dell G3 computer.

How to check javascript syntax errors?

Error checking methods in JavaScript:

  • try- Limitations of catch (this method can be viewed in How does JavaScript handle errors?)

Unable to catch syntax errors (because the code does not run at all..)

You need to use tools to add all function blocks and file blocks to try. Use catch

  • to usewindow.onerror

. Capture syntax errors and runtime errors;

You can get the error information, stack, error file, line number, and column number;

As long as the js script is executed on the current page Errors will be caught, such as: browser plug-in JavaScript, or exceptions thrown by flash, etc.

Cross-domain resources require special header support.

Common error handling procedures are as follows:

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中打印错误了 };

Recommended study: "javascript Advanced Tutorial"

The above is the detailed content of How to check javascript syntax errors. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn