[Switch] JavaScript Error Handling and Debugging - Points to Note in "Error Handling"

try-catchstatement

This statement is best for dealing with errors that are beyond our control, and it is not appropriate to use this statement when we clearly know that our code will fail.

The third edition of ECMA-262 introduced the try-catch statement. The basic syntax is as follows:

try {
    // statements
} catch(e) {
    // statements
    console.log(e); } 

Even if you don't use this error object, have a name, the actual information contained in the object varies from browser to browser, but what is common is a file that holds the error message.

  • messageattribute, ECMA-262 also specifies a storage error type

  • nameAttributes

All browsers support this property (except versions prior to Opera 9).

try {
    document.getElementByIfd("fdsa");
} catch(e) {
    // statements console.log(e.message); //document.getElementByIfd is not a function console.log(e.name); //TypeError } 

Another example:

try {
    var x = 1;
    var y = 0; console.log(z); } catch(e) { // statements console.log(e.message); //z is not defined console.log(e.name); //ReferenceError } 

finallyclause

Although optional in a try-catch block, once the finally clause is used, it will be executed no matter what, not even the return statement will block, for example:

function test() {
    try { return 1; } catch (error) { return 2; } finally { return 3; } } 

The above code returns 3. When the code in try is executed normally, finally will be executed; when there is an error in the code in try, the catch code will be executed, and the finally code will also be executed.

error type

Each error has a corresponding error type, and when an error occurs, an error object of the corresponding type will be thrown. ECMA-262 defines 7 error types:

* `Error`: 基类型。
* `EvalError`: 使用eval()函数发生异常时抛出。
* `RangeError`: 数值超出相应范围时抛出。
* `ReferenceError`: 找不到对象时抛出。
* `SyntaxError`: 使用eval()函数中的字符串有语法错误时抛出。
* `TypeError`: 在变量中保存意外类型或访问不存在的方法时抛出。
* `URIError`: 使用encodeURI或decodeURI()中URI格式不正确时抛出。

throw error

There is another one that matches try-catch

  • throwoperator to throw custom errors.

When throwing an error, you must specify a value for the throw operator. The type of this value is not required, for example:

throw 123;
throw "Hello World!";

The code stops executing immediately when the throw operator is encountered.

It can be more true by using some built-in error type

Such as:

try {
    throw new Error("nooo"); } catch (e) { console.log(e.message); //nooo console.log(e.name); //Error } 

or:

throw new SyntaxError("wwwwtttttfffff");

It is also possible to create custom error types:

function CustomError (message) {
    this.name = "CustomError"; this.message = message; } CustomError.prototype = new Error(); var somebug = new CustomError("wtf"); try { throw somebug } catch(e) { console.log(e.name); //CustomError console.log(e.message); //wtf } 

The purpose of catching errors is to prevent the browser from handling them by default; the purpose of throwing errors is to provide a message about why the error occurred.

error event

Errors that are not handled by try-catch will trigger the window object

  • errorevent. In any browser, the onerror event handler does not create an event object, but it accepts 3 parameters: the error message, the URL where the error is located, and the line number.

Whenever an error occurs, whether browser-generated or not, the error event is fired and this event handler is executed. Returning false in the event handler prevents the browser's default behavior of reporting errors, for example:

throw new Error("hello there");
window.onerror = function() { console.log(message); //Uncaught Error: hello there return false; } 

Images also support error events, which are fired whenever the URL in the image's src attribute does not return a recognized image format.

var x = new Image();
x.onerror = function () { console.log("message"); //message }; x.src = "fds.png"; 

common error types

Three common types of errors are:

  • type conversion error

  • wrong data type

  • communication error

type conversion error

Type conversion errors often occur when using an operator or automatically converting data types

The first common mistake is to use the equality and inequality operators

console.log(1 == "1"); //true
console.log(1 == true); //true 

Improvement: Congruence ( === ) and non-equality ( !== ) operators are recommended to avoid type conversion errors caused by using equality and inequality operators;

console.log(1 === "1"); //false
console.log(1 === true); //false 

A second common mistake is using a non-boolean value in a flow control statement.

function concat(str1, str2) {
    if (str2) { return str1 + str2; } else { return str1; } } concat('a', 0); //a" concat('a', 1); //"a1" 

The purpose of this method is to return the result of concatenating two strings when the second parameter exists;

When the second parameter does not exist, the first parameter is returned directly. However, in addition to undefined being converted to the boolean value false, 0 is also converted to false, and 1 is converted to true. Therefore, the result of the call is not consistent with the original intention.

Improve:

function concat(str1, str2) {
    if (typeof str2 == "string") { return str1 + str2; } else { return str1; } } concat('a', 0); //a" concat('a', 1); //"a" 

wrong data type

In JavaScript, type checking is not performed automatically before using variables and function parameters. Therefore, developers need to write their own code for data type checking. For example:

function reverseSort(values) {
    if (values) { //这里的判断不能保证是数组类型
        values.sort(); values.reverse(); } console.log(values); } reverseSort("a"); //TypeError 

Here, if the incoming parameter is not an array type, a data type error will occur. Generally speaking, typeof is used for type checking for basic types, and instanceof is used for type checking for object types.

function reverseSort(values) {
    if (values instanceof Array) { values.sort(); values.reverse(); } console.log(values); } reverseSort("a"); //a" reverseSort([6, 2, 3, 8, 1, 5]); //[8, 6, 5, 3, 2, 1] 

communication error

Scenario one is when the data is not encoded using encodeURIComponent() before sending it to the server. For example:

www.cnblogs.com ? backurl = http : //www.cnblogs.com?a=1

The solution is to use encodeURIComponent() to encode the parameters behind the backurl, the result is:

www.cnblogs.com ? backurl = http % 3 A % 2 F % 2 Fwww.cnblogs.com % 3 Fa % 3 D1 

The second scenario is that for the query string, the name and value of the query parameter are also encoded.

log errors to the server

If the front-end and back-end error information is collected and recorded in a centralized manner, the analysis of database error logs can be greatly facilitated. To record JavaScript errors to the server, the image control needs to be used, because all browsers support image objects, and cross-domain can be avoided. limit.

First create a server-side page for handling error data. This page gets error data from the query string, and then writes the data to the error log, for example, the page is a.ashx.

Then in the calling page, create an image object and assign a value to its src attribute, so that the error message can be sent to the server page.

 
function logError(msg) {
    var img = new Image(); img.src = 'a.ashx?msg=' + encodeURIComponent(msg); }

Original: https://segmentfault.com/a/1190000004447631

you may be interested in

  1. Detailed explanation of 10 major JavaScript errors from 1000+ project data analysis
  2. Catch unhandled Promise errors
  3. 10 common JavaScript bugs and how to fix them

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324947058&siteId=291194637