Home Web Front-end JS Tutorial Summary of using errors thrown by JS

Summary of using errors thrown by JS

Jun 04, 2018 am 10:24 AM
javascript use Summary

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.');
Copy after login

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';
Copy after login

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();
Copy after login

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');
}
Copy after login

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.');
  }
}
Copy after login

现在给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;
}
Copy after login

这个函数本来只是简单地给一个给定的元素增加一个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;
}
Copy after login

如果一个函数只被已知的实体调用,错误检查很可能没有必要(这个案例是私有函数);如果不能提前确定函数会被调用的所有地方,你很可能需要一些错误检查。这就更有可能从抛出自己的错误中获益。抛出错误最佳的地方是在工具函数中,如addClass()函数,它是通用脚本环境中的一部分,会在很多地方使用,更准确的案例是JS类库。

针对已知条件引发的错误,所有的JS类库都应该从它们的公共接口里抛出错误。如jQuery、YUI和Dojo等大型的库,不可能预料你在何时何地调用了它们的函数。当你做错事的时候通知你是它们的责任,因为你不可能进入库代码中去调试错误的原因。函数调用栈应该在进入库代码接口时就终止,不应该更深了。没有比看到由一打库代码中函数调用时发生一个错误更加糟糕的事情了吧,库的开发者应该承担起防止类似情况发生的责任。

私有JS库也类似。许多Web应用程序都有自己专用的内置的JS库或“拿来”一些有名的开源类库(类似jQuery)。类库提供了对脏的实现细节的抽象,目的是让开发者用得更爽。抛出错误有助于对开发者安全地隐藏这些脏的实现细节。

这里有一些关于抛出错误很好的经验法则:

一旦修复了一个很难调试的错误,尝试增加一两个自定义错误。当再次发生错误时,这将有助于更容易地解决问题。

如果正在编写代码,思考一下:“我希望[某些事情]不会发生,如果发生,我的代码会一团糟糕”。这时,如果“某些事情”发生,就抛出一个错误。

如果正在编写的代码别人(不知道是谁)也会使用,思考一下他们使用的方式,在特定的情况下抛出错误。

请牢记,我们目的不是防止错误,而是在错误发生时能更加容易地调试。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

jscss基础操作总结

为什么web开发中需要避免使用全局变量

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!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1657
14
PHP Tutorial
1257
29
C# Tutorial
1230
24
How to use magnet links How to use magnet links Feb 18, 2024 am 10:02 AM

Magnet link is a link method for downloading resources, which is more convenient and efficient than traditional download methods. Magnet links allow you to download resources in a peer-to-peer manner without relying on an intermediary server. This article will introduce how to use magnet links and what to pay attention to. 1. What is a magnet link? A magnet link is a download method based on the P2P (Peer-to-Peer) protocol. Through magnet links, users can directly connect to the publisher of the resource to complete resource sharing and downloading. Compared with traditional downloading methods, magnetic

How to use mdf and mds files How to use mdf and mds files Feb 19, 2024 pm 05:36 PM

How to use mdf files and mds files With the continuous advancement of computer technology, we can store and share data in a variety of ways. In the field of digital media, we often encounter some special file formats. In this article, we will discuss a common file format - mdf and mds files, and introduce how to use them. First, we need to understand the meaning of mdf files and mds files. mdf is the extension of the CD/DVD image file, and the mds file is the metadata file of the mdf file.

What software is crystaldiskmark? -How to use crystaldiskmark? What software is crystaldiskmark? -How to use crystaldiskmark? Mar 18, 2024 pm 02:58 PM

CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

How to download foobar2000? -How to use foobar2000 How to download foobar2000? -How to use foobar2000 Mar 18, 2024 am 10:58 AM

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

Simple guide to pip mirror source: easily master how to use it Simple guide to pip mirror source: easily master how to use it Jan 16, 2024 am 10:18 AM

Get started easily: How to use pip mirror source With the popularity of Python around the world, pip has become a standard tool for Python package management. However, a common problem that many developers face when using pip to install packages is slowness. This is because by default, pip downloads packages from Python official sources or other external sources, and these sources may be located on overseas servers, resulting in slow download speeds. In order to improve download speed, we can use pip mirror source. What is a pip mirror source? To put it simply, just

BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? Apr 26, 2024 am 09:40 AM

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

How to use NetEase Mailbox Master How to use NetEase Mailbox Master Mar 27, 2024 pm 05:32 PM

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

How to use Baidu Netdisk app How to use Baidu Netdisk app Mar 27, 2024 pm 06:46 PM

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

See all articles