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

MySQL 5.7.31 64-bit free installation version tutorial diagram

1. Download Download address: https://dev.mysql.c...

Detailed explanation of Docker data backup and recovery process

The data backup operation is very easy. Execute t...

How to install MySQL 5.7.17 and set the encoding to utf8 in Windows

download MySQL official download, select Windows ...

Summary of pitfalls in virtualbox centos7 nat+host-only networking

Table of contents 1. Problem Background 2. What a...

Vue implements fuzzy query-Mysql database data

Table of contents 1. Demand 2. Implementation 3. ...

Detailed explanation of JavaScript progress management

Table of contents Preface question principle test...

Docker Compose installation and usage steps

Table of contents 1. What is Docker Compose? 2. D...

How to use default values ​​for variables in SASS

Variables defined in SASS, the value set later wi...

Implementation of pushing Docker images to Docker Hub

After the image is built successfully, it can be ...

Detailed explanation of jQuery's copy object

<!DOCTYPE html> <html lang="en"...

Detailed explanation of docker network bidirectional connection

View Docker Network docker network ls [root@maste...

How to deploy FastDFS in Docker

Install fastdfs on Docker Mount directory -v /e/f...

Can't connect to local MySQL through socket '/tmp/mysql.sock' solution

Error message: ERROR 2002: Can't connect to l...