国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Web Front-end JS Tutorial A Guide to Proper Error Handling in JavaScript

A Guide to Proper Error Handling in JavaScript

Feb 16, 2025 pm 01:20 PM

A Guide to Proper Error Handling in JavaScript

Key Points

  • Cleverly use the try…catch statement block to effectively manage exceptions, enhancing the debugging process by allowing errors to bubble up to the call stack, thereby displaying errors more clearly.
  • Implement global error handlers (such as window.onerror events) to centralize and simplify error handling for easy management and maintenance in different parts of the application.
  • Use the browser's ability to record detailed error information (including call stack) to improve error diagnosis and have a clearer understanding of the source and context of the error.
  • Fix the asynchronous error handling puzzle by using try…catch in the setTimeout block or using a global error handler suitable for all execution contexts, ensuring that errors in asynchronous code are effectively captured and managed.
  • Enhance error messages by creating custom error types or enriching error messages, making it easier to identify and resolve specific issues and improve the overall robustness of JavaScript code.

Error handling in JavaScript is full of challenges. Follow Murphy's Law, anything that can go wrong will go wrong. This article will explore error handling in JavaScript, cover traps, best practices, and explain asynchronous code and Ajax as examples.

This article was updated on June 8, 2017 to address reader feedback. Specifically, file names have been added to the code snippet, unit tests have been cleaned, wrapper patterns have been added to uglyHandler, and sections about CORS and third-party error handlers have been added.

I think JavaScript's event-driven paradigm adds richness to the language. I like to think of my browser as this event-driven machine, and errors are no exception. When an error occurs, an event will be thrown at a certain moment. In theory, it can be said that errors are just simple events in JavaScript.

If you find this strange, please wear your seat belt as you will have a pretty wonderful journey. In this article, I will only focus on client-side JavaScript.

This topic is based on the concept explained in "Excellent Exception Handling in JavaScript". If you are not familiar with it, I recommend reading the basics. This article also assumes that you have moderate level of JavaScript knowledge. If you want to improve your level, why not sign up for SitePoint Premium and watch our course JavaScript: Next? The first lesson is free.

In either case, my goal is to explore the necessary conditions beyond handling exceptions. After reading this article, the next time you see a good try...catch block, you will think twice before you act.

Demo

The demo program to be used in this article can be found on GitHub, which is presented as follows:

A Guide to Proper Error Handling in JavaScript

All buttons will detonate a "bomb" when clicked. This bomb simulates an exception thrown as a TypeError. The following is the definition of this module:

// scripts/error.js

function error() {
  var foo = {};
  return foo.bar();
}

First, this function declares an empty object named foo. Please note that bar() is not defined anywhere. Let's use a good unit test to verify that this will detonate a bomb:

// tests/scripts/errorTest.js

it('throws a TypeError', function () {
  should.throws(error, TypeError);
});

This unit test uses Mocha for test assertions and uses Should.js for assertions. Mocha is a test runner, and Should.js is the assertion library. If you are not familiar with it, feel free to explore the test API. The test starts with it('description') and ends with a pass/failure in should. Unit tests run on Node and do not require a browser. I recommend you pay attention to these tests, as they prove the key concepts with pure JavaScript.

After cloning the repository and installing the dependencies, you can run the tests using npm t. Alternatively, you can run this single test like this: ./node_modules/mocha/bin/mocha tests/scripts/errorTest.js.

As shown, error() defines an empty object and then tries to access a method. Since bar() does not exist in the object, it throws an exception. Trust me, for dynamic languages ??like JavaScript, this happens to everyone!

Poor handling

There are some bad error handling next. I've abstracted the handler on the button from the implementation. Here is what the handler looks like:

// scripts/badHandler.js

function badHandler(fn) {
  try {
    return fn();
  } catch (e) { }
  return null;
}

This handler receives a fn callback as a parameter. This callback is then called within the handler function. Unit tests show what it is for:

// tests/scripts/badHandlerTest.js

it('returns a value without errors', function() {
  var fn = function() {
    return 1;
  };

  var result = badHandler(fn);

  result.should.equal(1);
});

it('returns a null with errors', function() {
  var fn = function() {
    throw new Error('random error');
  };

  var result = badHandler(fn);

  should(result).equal(null);
});

As you can see, if something goes wrong, this bad error handler will return null. The callback fn() can point to a legal method or a bomb.

The following click event handler explains the rest of the story:

// scripts/badHandlerDom.js

(function (handler, bomb) {
  var badButton = document.getElementById('bad');

  if (badButton) {
    badButton.addEventListener('click', function () {
      handler(bomb);
      console.log('Imagine, getting promoted for hiding mistakes');
    });
  }
}(badHandler, error));

Oops, I only get one null. This left me ignoring nothing when I tried to figure out what went wrong. This silent failure strategy ranges from bad user experience to data corruption. It's frustrating that I might spend hours debugging the symptoms and ignore the try-catch block. This evil handler will swallow up errors in the code and pretend everything is OK. This may be acceptable for organizations that do not value code quality. However, hiding errors can cause you to spend hours in the future to debug. In a multi-layer solution with a deep call stack, it is impossible to find out where the error is going. As far as error handling is concerned, this is very bad.

Silent failure strategy will make you desire better error handling. JavaScript provides a more elegant way to handle exceptions.

(The following content is similar to the previous output, except that the language and expression have been adjusted subtly to keep the article concise and avoid duplication.)

... (The rest is similar to the previous output, except that the language and expression are adjusted subtly to keep the article concise and avoid duplication.) ...

The above is the detailed content of A Guide to Proper Error Handling in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Why should you place  tags at the bottom of the ? Why should you place tags at the bottom of the ? Jul 02, 2025 am 01:22 AM

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

How to work with dates and times in js? How to work with dates and times in js? Jul 01, 2025 am 01:27 AM

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

What is event bubbling and capturing in the DOM? What is event bubbling and capturing in the DOM? Jul 02, 2025 am 01:19 AM

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

How can you reduce the payload size of a JavaScript application? How can you reduce the payload size of a JavaScript application? Jun 26, 2025 am 12:54 AM

If JavaScript applications load slowly and have poor performance, the problem is that the payload is too large. Solutions include: 1. Use code splitting (CodeSplitting), split the large bundle into multiple small files through React.lazy() or build tools, and load it as needed to reduce the first download; 2. Remove unused code (TreeShaking), use the ES6 module mechanism to clear "dead code" to ensure that the introduced libraries support this feature; 3. Compress and merge resource files, enable Gzip/Brotli and Terser to compress JS, reasonably merge files and optimize static resources; 4. Replace heavy-duty dependencies and choose lightweight libraries such as day.js and fetch

A definitive JS roundup on JavaScript modules: ES Modules vs CommonJS A definitive JS roundup on JavaScript modules: ES Modules vs CommonJS Jul 02, 2025 am 01:28 AM

The main difference between ES module and CommonJS is the loading method and usage scenario. 1.CommonJS is synchronously loaded, suitable for Node.js server-side environment; 2.ES module is asynchronously loaded, suitable for network environments such as browsers; 3. Syntax, ES module uses import/export and must be located in the top-level scope, while CommonJS uses require/module.exports, which can be called dynamically at runtime; 4.CommonJS is widely used in old versions of Node.js and libraries that rely on it such as Express, while ES modules are suitable for modern front-end frameworks and Node.jsv14; 5. Although it can be mixed, it can easily cause problems.

How to make an HTTP request in Node.js? How to make an HTTP request in Node.js? Jul 13, 2025 am 02:18 AM

There are three common ways to initiate HTTP requests in Node.js: use built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or send POST requests through .write(); 2.axios is a third-party library based on Promise. It has concise syntax and powerful functions, supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3.node-fetch provides a style similar to browser fetch, based on Promise and simple syntax

How does garbage collection work in JavaScript? How does garbage collection work in JavaScript? Jul 04, 2025 am 12:42 AM

JavaScript's garbage collection mechanism automatically manages memory through a tag-clearing algorithm to reduce the risk of memory leakage. The engine traverses and marks the active object from the root object, and unmarked is treated as garbage and cleared. For example, when the object is no longer referenced (such as setting the variable to null), it will be released in the next round of recycling. Common causes of memory leaks include: ① Uncleared timers or event listeners; ② References to external variables in closures; ③ Global variables continue to hold a large amount of data. The V8 engine optimizes recycling efficiency through strategies such as generational recycling, incremental marking, parallel/concurrent recycling, and reduces the main thread blocking time. During development, unnecessary global references should be avoided and object associations should be promptly decorated to improve performance and stability.

var vs let vs const: a quick JS roundup explainer var vs let vs const: a quick JS roundup explainer Jul 02, 2025 am 01:18 AM

The difference between var, let and const is scope, promotion and repeated declarations. 1.var is the function scope, with variable promotion, allowing repeated declarations; 2.let is the block-level scope, with temporary dead zones, and repeated declarations are not allowed; 3.const is also the block-level scope, and must be assigned immediately, and cannot be reassigned, but the internal value of the reference type can be modified. Use const first, use let when changing variables, and avoid using var.

See all articles