This is the fifth day of my participation in the August More text Challenge. For details, see: August More Text Challenge

preface

Javascript engines are single-threaded, so once an exception is encountered, the Javascript engine will usually stop execution, block subsequent code and throw an exception message, so for predictable exceptions, we should catch them and present them correctly to the user or developer.

The Error object

When a runtime Error occurs, an instance object of the Error is thrown. The error object has two properties: err.name: error name/error type err.message: error message

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

Error type JS defines the following seven error types:

  • Error
  • EvalError
  • RangeError
  • ReferenceError
  • SyntaxError
  • TypeError
  • URIError

throw

Some JavaScript code does not have syntax errors, but does have logic errors, for which JavaScript will not throw an exception. In this case, we can define an instance of an error object and use the throw statement to actively throw the exception. In a program, we can throw an exception for a purpose by using the throw statement. The syntax is as follows:

throw new Error("errorstatements")

The try… The catch… finally

  • Try Code where exceptions may occur
  • Catch (error) Code that has been executed incorrectly
  • Finally code that will execute anyway

There are three forms of the try declaration:

  • try… catch
  • try… finally
  • try… catch… finally

The rules of the finally

  • When infinallyBlock when an exception is throwntryBlock exception information
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
Copy the code
  • If fromfinallyBlock returns a value, then the value will become the entiretry-catch-finallyThe return value of, whether or not there isreturnStatements intrycatchIn the. This includes thecatchAn exception thrown in a block.
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
Copy the code

Try/Catch performance

One well-known deoptimization pattern is the use of try/catch

Use of try/catch statements in V8 (and possibly other JS engines) functions cannot be optimized by the V8 compiler.

window.onerror

By defining an event listener on window.onError, exceptions that are not caught by other code in the program will often be caught by the listener registered on window.onError

window.onerror = function (message, source, lineno, colno, error) {}Copy the code
  • Message: Exception message (string)
  • Source: URL (string) of the script where the exception occurred
  • Lineno: Number of the line where the exception occurred (number)
  • Colno: Number of the column where the exception occurred (numeric)
  • Error: Error object (object)

Exceptions in promises

An exception is thrown in a Promise

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

Catch an exception in the Promise

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

Pay attention to

In JavaScript functions, only return/yield/throw interrupts the function’s execution. Reject does not prevent it from continuing

Example:

No return reject

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

// before excute reject
// throw error
// after excute reject
Copy the code

I’m using return reject

Promise.resolve()
.then(() = > {
    console.log('before excute reject');
    return reject(new Error('throw error'));
    console.log('after excute reject'); //*** the difference is that the return will not be executed
})
.catch((err) = > {
    console.log(err.message);
});

// before excute reject
// throw error
Copy the code

Exception catching for Vue

Vue.config.errorHandler = (err, vm, info) = > {
  console.error("Errors caught with vue errorHandler");
  console.error(err);
  console.error(vm);
  console.error(info);
};
Copy the code