如何跳过或忽略 javascript/jquery 中的错误?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16096581/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I skip or ignore errors in javascript / jquery?
提问by Fredy
I suppose calling 3 javascript (jquery) files like this:
我想像这样调用 3 个 javascript (jquery) 文件:
<script type="text/javascript" src="js/file1.js"></script>
<script type="text/javascript" src="js/file2.js"></script>
<script type="text/javascript" src="js/file3.js"></script>
On file2.jsthere are script or function goes wrong, for example, the called function does not exist. The consequences because error in file2.jsare scripts in file3.jswill not be executed.
在file2.js上有脚本或函数出错,例如被调用的函数不存在。因为错误的后果file2.js是在脚本file3.js将不会被执行。
Whether there is a way to script in file3.jsstill executed? Possible to bypass or ignore the error on file2.js?
是否有办法让file3.js中的脚本仍然执行?可以绕过或忽略file2.js上的错误吗?
Thank you.
谢谢你。
回答by Ben McCormick
You can use a try catch block around the code with the error
您可以在带有错误的代码周围使用 try catch 块
try{
//code that causes an error
}catch(e){
functionToHandleError(e);
}
//continue from here
But you should only do that if the error is a known condition/unavoidable problem with an external library or only happens on bad user input. You shouldn't use it to allow the program to keep running at all costs.
但是,只有在错误是外部库的已知条件/不可避免的问题或仅在错误的用户输入时才应这样做。您不应该使用它来让程序不惜一切代价继续运行。
Some ways to avoid errors
一些避免错误的方法
- check that functions exist before calling them
- check that an object exists before referencing its properties
- if user input is involved, validate the input to check that it's the expected type/range/etc
- if this is a loading order problem consider reordering your scripts, or if this is a larger application using a dependency management system like requireJS
- if objects are undefined after an asynchronous request, remember that code does not wait on an async request and it will not be defined until afterwards. Code dealing with the provided values should be done in a callback function or using deffereds/promises.
- if you're referencing dom elements, consider starting your JS code from within a function that runs when the DOM is loaded such as jQuery's document.ready or the native window.onload.
- if javascript variables are declared without the
var
keyword, or are attached to a global object, they can be modified in places other than they are declared. Javascript also doesn't have block scope. Make sure you know all the places your variables are being modified, and try to limit the scope of your variables when possible. Especially avoid using too many global variables to hold state, as it can be difficult to know the current state without many null/type checks.
- 在调用它们之前检查函数是否存在
- 在引用其属性之前检查对象是否存在
- 如果涉及用户输入,请验证输入以检查它是否是预期的类型/范围/等
- 如果这是一个加载顺序问题,请考虑重新排序您的脚本,或者如果这是一个使用依赖管理系统(如 requireJS)的较大应用程序
- 如果在异步请求之后对象未定义,请记住代码不会等待异步请求,并且直到之后才会定义它。处理提供的值的代码应该在回调函数中或使用 defereds/promises 完成。
- 如果您正在引用 dom 元素,请考虑从加载 DOM 时运行的函数(例如 jQuery 的 document.ready 或本机 window.onload)中启动您的 JS 代码。
- 如果 javascript 变量在没有
var
关键字的情况下声明,或者附加到全局对象,则可以在声明之外的地方修改它们。Javascript 也没有块作用域。确保您知道变量被修改的所有位置,并在可能的情况下尝试限制变量的范围。尤其要避免使用过多的全局变量来保存状态,因为如果没有很多空/类型检查,很难知道当前状态。
Some ways to handle errors
处理错误的一些方法
If its an expected problem (IE if the input may be empty and requires different handling), ideally check it with an if statement beforehand. If you don't want to do that, you can use try/catch to cast the input, ask for new input, or act on the input given as approperiate.
if its an unexpected problem (IE you don't know whats going on) a catch block can be a good place to output diagnostic information during development. IE, don't just catch it and let it fail silently, output a message to let you or other developers know where it failed, and then use your favorite browser's web developer tools to inspect the values at the time, figure out what happened, and add handling for that case to fix it.
如果它是一个预期的问题(即如果输入可能是空的并且需要不同的处理),最好事先用 if 语句检查它。如果您不想这样做,您可以使用 try/catch 来转换输入、请求新输入或根据给定的输入执行适当的操作。
如果是意外问题(即您不知道发生了什么),catch 块可能是在开发过程中输出诊断信息的好地方。IE,不要只是捕捉它,让它默默地失败,输出一条消息让你或其他开发人员知道它失败的地方,然后使用你最喜欢的浏览器的web开发人员工具检查当时的值,弄清楚发生了什么,并为该案例添加处理以修复它。
What not to do
什么不该做
put the try/catch in, and then just let the program keep on running. If the code that isn't running correctly is unnecessary, get rid of it. If it is necessary and isn't working correctly, fix it.
use try catches as your input validation (IE if the function is null it will throw an exception and I'll catch it, then I know the function is null). Whenever possible, check for any expected errors. Try/catches should handle "exceptions" when the behavior is unusual and you need to go down an alternative code path or alert the user that something is wrong.
放入 try/catch,然后让程序继续运行。如果运行不正确的代码是不必要的,请删除它。如果有必要并且不能正常工作,请修复它。
使用 try catches 作为您的输入验证(即,如果函数为空,它将抛出异常,我会捕获它,然后我知道该函数为空)。只要有可能,检查是否有任何预期的错误。当行为异常并且您需要使用替代代码路径或提醒用户出现问题时,尝试/捕获应该处理“异常”。
回答by Jamil Bashir
When you don't have time to debug try this:
当你没有时间调试时,试试这个:
function stoperror() {
return true;
}
Call it:
称它为:
window.onerror = stoperror;
The functionality is very simple: create a function that always returns true, and then whenever an error occurs, call this function (returning true and suppressing the error).
功能很简单:创建一个总是返回true的函数,然后每当发生错误时,调用这个函数(返回true并抑制错误)。
回答by Muhammad Tahir
you can save yourself from "function is undefined" by using this
你可以通过使用这个来避免“函数未定义”
//Simple function that will tell if the function is defined or not
function is_function(func) {
return typeof window[func] !== 'undefined' && $.isFunction(window[func]);
}
//usage
if (is_function("myFunction") {
alert("myFunction defined");
} else {
alert("myFunction not defined");
}
回答by PSR
you can use try and catch statements.And check for null by using != null
condition
您可以使用 try 和 catch 语句。并使用!= null
条件检查 null
try{
}catch(e){
}
回答by Justin Helgerson
Wrap the call that results in an error in a try...catch block:
将导致错误的调用包装在 try...catch 块中:
try {
callNonExistentMethod();
}
catch (e) {
//Handle the error if you wish.
}
回答by TGH
I would suggest adding proper null checks around objects(including functions) before assuming they exist,so that the code will fail gracefully.
我建议在假设对象存在之前在对象(包括函数)周围添加适当的空检查,以便代码正常失败。
Here are some ideas: Javascript check if function exists
这里有一些想法: Javascript 检查函数是否存在