The most complete guide to JavaScript error handling (top half)

Time:2021-7-28

By Valentino Gagliardi
Translator: front end Xiaozhi
Source: valentinog

Like it and see it again, wechat search[move to the world]Pay attention to this person who has no big factory background, but has an upward positive attitude. this paperGitHubhttps://github.com/qq44924588… It has been included in the, the articles have been classified, and a lot of my documents and tutorial materials have been sorted out.

Everyone said that there was no project in the resume, so I helped you find a project and attached [construction tutorial].

What is a programming error

Our development process is not always smooth sailing. Especially in some cases, we may want to stop the program or notify the user when something bad happens.

For example:

  • The program attempted to open a file that does not exist
  • Network connection disconnected
  • Invalid character entered by user

In such cases, we can write a custom error to manage, or directly let the engine define these errors for us. With the error definition, we can notify the user with a message or stop the execution program.

What are the errors in JavaScript

The error in JavaScript is an object. To create an error in JS, you can useErrorThe objects are as follows:

Const err = new error ('ho Ho, something seems to be wrong! ')

It can also be omittednewkeyword:

Const err = error ('hoho, something seems to be wrong! ')

When creating an error object, it has three properties:

  • message: string with error message
  • name: wrong type
  • stack: stack trace of function execution

For example, we useTypeErrorObject creates an error, corresponding tomessageIs the incoming word symbol created,nameyes“TypeError” 😀

Const wrong type = typeerror ("Ho Ho, something seems to be wrong!")

Wrong type. Message // "Ho Ho, something seems to be wrong!"
wrongType.name // "TypeError"

There are many types of errors in JavaScript

There are many types of errors in JavaScript, such as:

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

Remember that all of these error types are actual constructors, meaning that a new error object is returned.

In our code, we mainly useErrorandTypeErrorThese two most common types are used to create their own error objects.

Most of the time, most of the errors will come directly from the JavaScript engine, such asInternalErrororSyntaxError。

If you reassign toconstIs thrown when a variable is declaredTypeErrorWrong.

Const name = "front end Xiaozhi"
Name = "Wang Daye"

// // TypeError: Assignment to constant variable.

SyntaxErrorThe error is usually the wrong keyword, as shown below:

va x = '33';
// SyntaxError: Unexpected identifier

Or, when the keyword is in the wrong place, for exampleawaitandasyncUse of:

function wrong(){
    await 99;
}

wrong();

// SyntaxError: await is only valid in async function

the other oneTypeErrorAn example is to manipulate a non-existent DOM element on a page.

Uncaught TypeError: button is null

In addition to these built-in errors, there are:

  • DOMException
  • Domerror is now obsolete and no longer used.

DOMExceptionIs a series of errors related to the web API. When we perform stupid operations in the browser, they will be thrown, for example:

document.body.appendChild(document.cloneNode(true));

result:

Uncaught DOMException: Node.appendChild: May not add a Document as a child

What is an exception?

Most developers think that errors and exceptions are the same thing. actually,The error object becomes an exception only when thrown.

To throw an exception in JavaScript, we usethrowKeyword throw out errors:

Const wrong type = typeerror ("Ho Ho, something seems to be wrong!")

throw wrongType;

Short form:

Throw typeerror ("HOHO, something seems to be wrong!")

perhaps

Throw new typeerror ("HOHO, something seems to be wrong!")

It is unlikely to throw asynchrony outside the function body or condition. Consider the following example:

function toUppercase(string) {
  if (typeof string !== "string") {
    Throw typeerror ("HOHO, something seems to be wrong!");
  }

  return string.toUpperCase();
}

Here we check whether the function parameter is a string. If not, we throw an exception. Technically, you can throw anything in JavaScript, not just the error object

throw Symbol();
throw 33;
throw "Error!";
throw null;

However, it’s best to avoid these things: always throw the right error object instead of some basic types.

This contributes to consistency in error handling in the code. Other members can expect access on the wrong objecterror.messageorerror.stackTo know the source of the error.

Everyone said that there was no project in the resume, so I helped you find a project and attached [construction tutorial].

What happens when we throw an exception?

An exception is like a rising elevator: once you throw one, it will bubble in the program stack unless it is caught somewhere.

Consider the following codes:

function toUppercase(string) {
  if (typeof string !== "string") {
    Throw typeerror ("the parameter type needs to be string");
  }

  return string.toUpperCase();
}

toUppercase(4);

Run the code and you will see the following in the console:

Uncaught TypeError: Wrong type given, expected a string
    toUppercase http://localhost:5000/index.js:3
    <anonymous> http://localhost:5000/index.js:9

You can see the exact line where the error occurred.

This report is a stack trace that helps track problems in your code. Stack trace from bottom to top:

 toUppercase http://localhost:5000/index.js:3
    <anonymous> http://localhost:5000/index.js:9

In addition to seeing this stack trace in the browser’s console, you can also use the error object’sstackProperties.

If the exception is not caught, that is, the programmer does not take any measures to catch it, the program will crash.

When and where to catch exceptions in code depends on the specific use case.

For example, we might want to pass an exception in the stack to crash the program completely. This happens when it is safer to stop the program with errors than to process invalid data.

Next, let’s look at error and exception handling in JavaScript synchronization and asynchrony.

Error handling in synchronization

Synchronization code is simple in most cases, so its error handling is also simple.

Error handling of general functions

Synchronization codes are executed in the same order as they are written. Let’s look at the previous example:

function toUppercase(string) {
  if (typeof string !== "string") {
    Throw typeerror ("the parameter type needs to be string");
  }

  return string.toUpperCase();
}

toUppercase(4);

Here, the engine calls and executestoUppercase。 All this happens synchronously. To catch exceptions thrown by synchronization functions, we can usetry/catch/finally:

try {
  toUppercase(4);
} catch (error) {
  console.error(error.message);
} finally {
}

try/catch/finallyIs a synchronous structure, but it can also catch exceptions that occur asynchronously.

Use the generator function to handle errors

In JavaScriptgenerator function Is a special function. In addition to providing a two-way communication channel between its internal scope and users, it can also be used at willsuspendandrecovery。

To create a generator function, wefunctionKeyword followed by a*:

function* generate() {
  //
}

Can be used within a functionyieldReturn value:

function* generate() {
  yield 33;
  yield 99;
}

The return value of the generator function is aIterator objects (iterator object)。 To extract values from the generator, we can use two methods:

  • usenext()method
  • adoptfor...ofergodic

To get the value in the generator, as shown below:

function* generate() {
  yield 33;
  yield 99;
}

const go = generate();

const firstStep = go.next().value; // 33
const secondStep = go.next().value; // 99

Integrators can also work in other ways: they can receive values and exceptions returned by callers.

exceptnext()In addition, the iterator object returned from the generator also hasthrow()method. Using this method, we can stop the program by injecting an exception into the generator

function* generate() {
  yield 33;
  yield 99;
}

const go = generate();

const firstStep = go.next().value; // 33

Go. Throw (error ("I'm going to end you!");

const secondStep = go.next().value; //  An exception will be thrown here

To get this error, you can use it in the generator functiontry/catch/finally:

function* generate() {
  try {
    yield 33;
    yield 99;
  } catch (error) {
    console.error(error.message);
  }
}

The following example usesfor...ofTo get the value in the generator function:

function* generate() {
  yield 33;
  yield 99;
  
  Throw error ("I'm going to end you!")
}

try {
  for (const value of generate()) {
    console.log(value)
  }
} catch (error) {
  console.log(error.message)
}

/*Output:
  33
  99
  I want to end you!
*/

Error handling in asynchronous

JavaScript is synchronous in nature and is a single threaded language.

Hosting environments such as browser engines use many web APIs and enhance JS to interact with external systems and handle I / O bound operations.

Asynchronous operations in the browser include timer related functions, events and promise.

Error handling in asynchronous is different from synchronous error handling. Let’s look at some examples.

Everyone said that there was no project in the resume, so I helped you find a project and attached [construction tutorial].

Error handling of timer

Consider the following code snippet:

function failAfterOneSecond() {
  setTimeout(() => {
    throw Error("Something went wrong!");
  }, 1000);
}

This function throws an exception about 1 second later. What is the correct way to handle this exception?

The following methods do not work:

function failAfterOneSecond() {
  setTimeout(() => {
    throw Error("Something went wrong!");
  }, 1000);
}

try {
  failAfterOneSecond();
} catch (error) {
  console.error(error.message);
}

We knowtry/catchIt’s synchronization, andsetTimeoutIs asynchronous. When executed tosetTimeoutWhen calling back,try/catchIt has already run, so the exception cannot be caught.

They are on two different tracks:

Track A: --> try/catch
Track B: --> setTimeout --> callback --> throw

If you can make the program run, puttry/catchMove tosetTimeoutInside. However, this approach is of little significance. We will use promise to solve such problems later.

Error handling in event

DOM event operations (listening and triggering) are defined inEventTargetInterface.ElementNodedocumentNode andwindowObject, all of which have deployed this interface. In addition, XMLHttpRequestAudioNode、AudioContextThis interface is also deployed for browser built-in objects. The interface is three methods,addEventListenerandremoveEventListenerUsed to bind and remove listener functions,dispatchEventUsed to trigger events.

The error handling mechanism for DOM events follows the same scheme as any asynchronous web API.

Consider the following example:

const button = document.querySelector("button");

button.addEventListener("click", function() {
  throw Error("Can't touch this button!");
});

Here, an exception is thrown immediately after clicking the button. How do we catch it? The following methods do not work and will not prevent the program from crashing:

const button = document.querySelector("button");

try {
  button.addEventListener("click", function() {
    throw Error("Can't touch this button!");
  });
} catch (error) {
  console.error(error.message);
}

AndsetTimeoutLike,addEventListenerIt is also executed asynchronously.

Track A: --> try/catch
Track B: --> addEventListener --> callback --> throw

If you can make the program run, puttry/catchMove toaddEventListenerInside. However, this approach is of little significance. We will use promise to solve such problems later.

How about onerror

HTML elements have many event handlers, such asonclick,onmouseenter,onchangeWait, of courseonerror。

WhenimgLabel orscriptWhen a tag encounters a resource that does not exist,onerrorEvent handlers are triggered.

Consider the following example:

...
<body>
  <img>
</body>
...

When the file does not exist, the console will report the following error:

GET http://localhost:5000/nowhere-to-be-found.png
[HTTP/1.1 404 Not Found 3ms]

In JS, we canonerrorTo catch this error:

const image = document.querySelector("img");

image.onerror = function(event) {
  console.log(event);
};

Better way:

const image = document.querySelector("img");

image.addEventListener("error", function(event) {
  console.log(event);
});

This approach is useful in some cases where the requested resources are lost, butonerrorAndthrowAndtry/cathcirrelevant.


The bugs that may exist after code deployment cannot be known in real time. Afterwards, in order to solve these bugs, we spent a lot of time on log debugging. By the way, we recommend a useful bug monitoring tool fundebug.

Original text: https://www.valentinog.com/bl…

communication

The article is continuously updated every week and can be searched by wechat[move to the world]Read and reply at the first time[benefits]There are many front-end videos waiting for you, GitHub https://github.com/qq449245884/xiaozhi Already included, welcome star.

The most complete guide to JavaScript error handling (top half)

Recommended Today

Implementation example of go operation etcd

etcdIt is an open-source, distributed key value pair data storage system, which provides shared configuration, service registration and discovery. This paper mainly introduces the installation and use of etcd. Etcdetcd introduction etcdIt is an open source and highly available distributed key value storage system developed with go language, which can be used to configure sharing […]