Home > Article > Web Front-end > Summary of using errors thrown by JS
This time I will bring you a summary of the use of JS throwing errors and what are the precautions for JS throwing errors. The following is a practical case, let's take a look.
Throwing errors in JS is an art. It takes time to figure out where in your code it's appropriate to throw an error. So once you figure this out, your time debugging your code will be much shorter and your satisfaction with your code will increase dramatically.
The Nature of Error
A program raises an error when something unexpected happens. Perhaps an incorrect value was passed to a function, or a mathematical operation encountered an invalid operand. Programming language defines a basic set of rules, deviations from these rules will cause errors, and developers can then fix the code. Debugging is very difficult if errors are not thrown or reported to you. If all failures are silent, the first problem is that it will take a lot of time to find it, let alone isolate and fix it. Therefore, errors are a developer's friend, not their enemy.
Errors often pop up in unexpected places and at inappropriate times, which is very troublesome. Worse, the default error messages are often too terse to explain what exactly went wrong. JS error messages are notorious for being sparse and cryptic (especially in older versions of IE), which only compounds the problem. Imagine if an error popped up that said: "This function call failed because these conditions occurred." Then, the debugging task immediately becomes easier, which is the benefit of throwing your own errors.
It's helpful to think of errors like built-in failure cases. It's much easier to plan for a failure in a specific place in your code than to expect failure everywhere. This is a very common practice in product design, not just in coding. Cars also have crash-absorbing areas where the frame is designed to collapse in a predictable manner when an impact occurs. Knowing how these frames will react when a crash comes - specifically, which parts will fail - manufacturers will be able to keep passengers safe. Your code can also be created this way.
Throwing errors in JS
There is no doubt that throwing errors in JS is more valuable than doing the same thing in any other language, and this is due to the disadvantages of web-side debugging. Complexity. You can use the throw operator to throw a provided object as an error. Objects of any type can be thrown as errors, however, Error objects are most commonly used.
throw new Error('Something bad happened.');
The built-in Error type is valid in all JS implementations. Its constructor only accepts one parameter, which refers to the error message. When an error is thrown in this way, the browser usually displays the message (message string) directly if it is not caught by a try-catch statement. Most browsers today have a console, where error messages will be output once an error occurs. In other words, any errors you throw and those you don't throw are treated the same way.
Inexperienced developers sometimes directly throw a string as an error, such as:
// 不好的写法throw 'message';
This can indeed throw an error, but not all browsers respond Everything will be as you expected. Firefox, Opera and Chrome will all display an "uncaught exception" message and they contain the above message string. Safari and IE simply throw an "uncaught exception" error without providing the above message string at all, which is not helpful for debugging.
Obviously you can throw any type of data if you like. There is no rule constraint that cannot be a specific data type.
throw { name: 'Nicholas' };throw true;throw 12345;throw new Date();
Just one thing to keep in mind, any value thrown will raise an error if it is not captured by a try-catch statement. Firefox, Opera and Chrome will all call the String() function on the thrown value to complete the display logic of the error message, but this is not the case with Safari and IE. For all browsers, the only error-free way to display a custom error message is to use an Error object.
Benefits of throwing errors
Throwing your own errors allows you to use the exact text for the browser to display. In addition to row and column numbers, you can include any information you need to help debug the problem. I recommend always including the function name in the error message, as well as the reason why the function failed. Examine the following function:
function getDivs (element) { return element.getElementsByTagName('div'); }
This function is designed to obtain the div elements in all descendant elements under the element element. It may be common to pass a null value to a DOM element that is passed to a function to operate on, but what is actually needed is a DOM element. What happens if you pass null to this function? You will see a vague error message similar to "object expected". Then, you have to look at the execution stack and actually locate the problem in the source file. Debugging is easier by throwing an error:
function getDivs (element) { if (element && element.getElementsByTagName) { return element.getElementsByTagName('div'); } else { throw new Error('getDivs(): Argument must be a DOM element.'); } }
现在给getDivs()函数抛出一个错误,任何时候只要element不满足继续执行的条件,就会抛出一个错误明确地陈述发生的问题。如果在浏览器控制台中输出该错误,你马上能开始调试,并知道最有可能导致该错误的原因是调用函数试图用一个值为null的DOM元素去做进一步的事情。
我倾向于认为抛出错误就像给自己留下告诉自己为什么失败的标签。
何时抛出错误
理解了如何抛出错误只是等式的一个部分,另外一部分就是要理解什么时候抛出错误。由于JS没有类型和参数检查,大量的开发者错误地假设他们自己应该实现每个函数的类型检查。这种做法并不实际,并且会对脚本的整体性能造成影响。考察下面的函数,它试图实现充分的类型检查。
// 不好的做法:检查了太多的错误function addClass (element, className) { if (!element || typeof element.className !== 'string') { throw new Error('addClass(): First argument must be a DOM element.'); } if (typeof className !== 'string') { throw new Error('addClass(): Second argument must be a string.'); } element.className += '' + className; }
这个函数本来只是简单地给一个给定的元素增加一个CSS类名(className),因此,函数的大部分工作变成了错误检查。纵然它能在每个函数中检查每个参数(模仿静态语言),在JS中这么做也会引起过度的杀伤。辨识代码中哪些部分在特定的情况下最有可能导致失败,并只在那些地方抛出错误才是关键所在。
在上例中,最有可能引发错误的是给函数传递一个null引用值。如果第二个参数是null或者一个数字或者一个布尔值是不会抛出错误的,因为JS会将其强制转换为字符串。那意味着导致DOM元素的显示不符合期望,但这并不至于提高到严重错误的程度。所以,我只会检查DOM元素。
// 好的写法function addClass (element, className) { if (!element || typeof element.className !== 'string') { throw new Error('addClass(): First argument must be a DOM element.'); } element.className += '' + className; }
如果一个函数只被已知的实体调用,错误检查很可能没有必要(这个案例是私有函数);如果不能提前确定函数会被调用的所有地方,你很可能需要一些错误检查。这就更有可能从抛出自己的错误中获益。抛出错误最佳的地方是在工具函数中,如addClass()函数,它是通用脚本环境中的一部分,会在很多地方使用,更准确的案例是JS类库。
针对已知条件引发的错误,所有的JS类库都应该从它们的公共接口里抛出错误。如jQuery、YUI和Dojo等大型的库,不可能预料你在何时何地调用了它们的函数。当你做错事的时候通知你是它们的责任,因为你不可能进入库代码中去调试错误的原因。函数调用栈应该在进入库代码接口时就终止,不应该更深了。没有比看到由一打库代码中函数调用时发生一个错误更加糟糕的事情了吧,库的开发者应该承担起防止类似情况发生的责任。
私有JS库也类似。许多Web应用程序都有自己专用的内置的JS库或“拿来”一些有名的开源类库(类似jQuery)。类库提供了对脏的实现细节的抽象,目的是让开发者用得更爽。抛出错误有助于对开发者安全地隐藏这些脏的实现细节。
这里有一些关于抛出错误很好的经验法则:
一旦修复了一个很难调试的错误,尝试增加一两个自定义错误。当再次发生错误时,这将有助于更容易地解决问题。
如果正在编写代码,思考一下:“我希望[某些事情]不会发生,如果发生,我的代码会一团糟糕”。这时,如果“某些事情”发生,就抛出一个错误。
如果正在编写的代码别人(不知道是谁)也会使用,思考一下他们使用的方式,在特定的情况下抛出错误。
请牢记,我们目的不是防止错误,而是在错误发生时能更加容易地调试。
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of Summary of using errors thrown by JS. For more information, please follow other related articles on the PHP Chinese website!