JavaScript Basics: Error Capture Mechanism

JavaScript Basics: Error Capture Mechanism

Preface

The Javascript engine is single-threaded, so once an exception is encountered, the Javascript engine will usually stop executing, block subsequent code and throw an exception message. Therefore, for foreseeable exceptions, we should capture them and display them correctly to users or developers.

Error Object

When a runtime error occurs, an instance of Error will be thrown.

The error object has two properties:

  • err.name: Error name/Error type
  • err.message: error message

Creating an Error

new Error([message[,fileName[,lineNumber]]])

Error type js defines the following 7 error types:

  1. Error
  2. EvalError
  3. RangeError
  4. ReferenceError
  5. SyntaxError
  6. TypeError
  7. URIError

throw

Some JavaScript codes have no syntactic errors, but there are logical errors. For such errors, JavaScript will not throw an exception. At this time, we can define an instance of the error object ourselves and use the throw statement to actively throw an exception. In the program, we can purposefully throw exceptions by using the throw statement. Its syntax is as follows:

throw new Error("errorstatements")

try…catch…finally

  • try code where exceptions may occur
  • catch(error) Code executed when an error occurs
  • finally Code that will be executed no matter what

There are three forms of try statements:

  • try...catch
  • try...finally
  • try...catch...finally

The finally rule

When an exception is thrown in the finally block, the exception in the try block will be overwritten.

try {
    try {
        throw new Error('can not find it1');
    finally
        throw new Error('can not find it2');
    }
} catch (err) {
    console.log(err.message);
}

// can not find it2

If you return a value from the finally block, that value will become the return value of the entire try-catch-finally, regardless of whether there are return statements in the try and catch. This includes exceptions thrown in catch blocks.

function test() {
    try {
        throw new Error('can not find it1');
        return 1;
    } catch (err) {
        throw new Error('can not find it2');
        return 2;
    finally
        return 3;
    }
}

console.log(test()); // 3

Try / Catch Performance

A well-known anti-optimization pattern is to use try/catch

In V8 (and possibly other JS engines), functions using try/catch statements cannot be optimized by the V8 compiler.

window.onerror

By defining an event listener function on window.onerror, uncaught exceptions generated by other code in the program will often be caught by the listener function registered on window.onerror

window.onerror = function (message, source, lineno, colno, error) { }

  • message: exception information (string)
  • source: URL of the script where the exception occurred (string)
  • lineno: The line number where the exception occurred (a number)
  • colno: The column number where the exception occurred (number)
  • error : Error object (object)

Exceptions in Promises

Exception thrown in Promise

  • new Promise((resolve,reject)=>{ reject(); })
  • Promise.resolve().then((resolve,reject)=>{ reject(); });
  • Promise.reject();
  • throw expression;

Catching exceptions in Promise

  • promiseObj.then(undefined, (err)=>{ catch_statements });
  • promiseObj.catch((exception)=>{ catch_statements })

Notice

In a JavaScript function, only return / yield / throw will interrupt the execution of the function, and reject will not prevent further execution.

Example:

Reject without return

Promise.resolve()
.then(() => {
    console.log('before execute reject');
    reject(new Error('throw error'));
    console.log('after execute reject');
})
.catch((err) => {
    console.log(err.message);
});

// before execute reject
// throw error
// after execute reject

Reject using return

Promise.resolve()
.then(() => {
    console.log('before execute reject');
    return reject(new Error('throw error'));
    console.log('after execute reject'); //*** The difference is here, if return is returned, it will not be executed here})
.catch((err) => {
    console.log(err.message);
});

// before execute reject
// throw error

Vue exception capture

Vue.config.errorHandler = (err, vm, info) => {
  console.error("Error captured by vue errorHandler");
  console.error(err);
  console.error(vm);
  console.error(info);
};

Summarize

This is the end of this article about the error catching mechanism for JavaScript basics. For more relevant js error catching mechanism content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • How to capture and report Js errors using window.onerror
  • Summary of some things about JS asynchronous error capture
  • Analysis of the usage of try catch exception capture mechanism in javascript
  • JS uses onerror to capture exceptions example
  • Detailed Analysis of Events and Exception Capture in JavaScript

<<:  Dynamic SQL statement analysis in Mybatis

>>:  Linux Check the installation location of the software simple method

Recommend

Security configuration and detection of SSL after the website enables https

It is standard for websites to enable SSL nowaday...

Linux CentOS 6.5 Uninstall, tar and install MySQL tutorial

Uninstall the system-provided MySQL 1. Check whet...

How to use less in WeChat applet (optimal method)

Preface I am used to writing less/sass, but now I...

Interviewers often ask questions about React's life cycle

React Lifecycle Two pictures to help you understa...

How Database SQL SELECT Queries Work

As Web developers, although we are not profession...

Clean XHTML syntax

Writing XHTML demands a clean HTML syntax. Writing...

Summary of the execution issues between mysql max and where

Execution problem between mysql max and where Exe...

jQuery implements time selector

This article example shares the specific code of ...

Detailed explanation of how to copy and backup docker container data

Here we take the Jenkins container as an example ...

How to create a my.ini file in the MySQL 5.7.19 installation directory

In the previous article, I introduced the detaile...

Detailed explanation of JS browser storage

Table of contents introduction Cookie What are Co...

JS implements the sample code of decimal conversion to hexadecimal

Preface When we write code, we occasionally encou...

Summary of coalesce() usage tips in MySQL

Preface Recently, I accidentally discovered MySQL...

How to manually scroll logs in Linux system

Log rotation is a very common function on Linux s...

Vue implements tab navigation bar and supports left and right sliding function

This article mainly introduces: using Vue to impl...