Home Web Front-end JS Tutorial How to handle errors in JavaScript

How to handle errors in JavaScript

Jan 26, 2018 am 10:15 AM
javascript js Way

The event-driven paradigm of JavaScript adds richness to the language and makes programming with JavaScript more diverse. If you think of the browser as an event-driven tool for JavaScript, then when an error occurs, an event will be thrown. It is theoretically possible to think that these errors are just simple events in JavaScript.

This article will discuss error handling in client-side JavaScript. Mainly introduces common mistakes, error handling, asynchronous code writing, etc. in JavaScript.

Let’s take a look at how to correctly handle errors in JavaScript.

Demo demonstration

The demo used in this article can be found on GitHub. After running, the page will look like this:

Each The button will raise an "Error (Exception)", and this error will simulate a thrown exception TypeError. The following is the definition of the module:

// scripts/error.js
function error() {
 var foo = {};
 return foo.bar();
}
Copy after login

First, this function declares an empty object foo. Note that bar() is not defined anywhere. Next, verify whether this unit test will raise an "error":

// tests/scripts/errorTest.js
it('throws a TypeError', function () {
 should.throws(error, TypeError);
});
Copy after login

This unit test is in Mocha, and there is a test declaration in Should.js. Mocha is the test runner tool and Should.js is the assertion library. This unit test runs on Node and does not require the use of a browser.

error() defines an empty object and then tries to access a method. Because bar() does not exist within the object, an exception will be thrown. This error that occurs in dynamic languages ​​like JavaScript may happen to everyone!

Error handling (1)

Use the following code to handle the above error:

// scripts/badHandler.js
function badHandler(fn) {
 try {
  return fn();
 } catch (e) { }
 return null;
}
Copy after login

The handler takes fn as an input parameter, and then fn will be processed inside the handler function is called. Unit testing will reflect the role of the above error handler:

// 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);
});
Copy after login

If a problem occurs, the error handler will return null. The fn() callback function can point to a legal method or error.

The following click events will continue event processing:

// 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));
Copy after login

This processing method hides an error in the code and is difficult to find. Hidden errors can take hours of debugging time. Especially in multi-layer solutions with deep call stacks, this error can be harder to find. So this is a very poor way of handling errors.

Error handling (2)

The following is another error handling method.

// scripts/uglyHandler.js
function uglyHandler(fn) {
 try {
  return fn();
 } catch (e) {
  throw new Error('a new error');
 }
}
Copy after login

The way to handle exceptions is as follows:

// tests/scripts/uglyHandlerTest.js
it('returns a new error with errors', function () {
 var fn = function () {
  throw new TypeError('type error');
 };
 should.throws(function () {
  uglyHandler(fn);
 }, Error);
});
Copy after login

The above has obvious improvements to the error handler. Here the exception will bubble up the call stack. At the same time, the error will expand the stack, which is very helpful for debugging. In addition to throwing an exception, the interpreter will look for additional processing along the stack. This also brings the possibility of handling errors from the top of the stack. But this is still poor error handling, requiring us to trace the original exception step by step down the stack.

An alternative can be adopted to end this poor error handling with a custom error method. This approach becomes helpful as you add more details to the error.

For example:

// scripts/specifiedError.js
// Create a custom error
var SpecifiedError = function SpecifiedError(message) {
 this.name = 'SpecifiedError';
 this.message = message || '';
 this.stack = (new Error()).stack;
};
SpecifiedError.prototype = new Error();
SpecifiedError.prototype.constructor = SpecifiedError;
// scripts/uglyHandlerImproved.js
function uglyHandlerImproved(fn) {
 try {
  return fn();
 } catch (e) {
  throw new SpecifiedError(e.message);
 }
}
// tests/scripts/uglyHandlerImprovedTest.js
it('returns a specified error with errors', function () {
 var fn = function () {
  throw new TypeError('type error');
 };
 should.throws(function () {
  uglyHandlerImproved(fn);
 }, SpecifiedError);
});
Copy after login

The specified error adds more details and preserves the original error message. With this improvement, the above processing is no longer a poor processing method, but a clear and useful method.

After the above processing, we also received an unhandled exception. Next let's see how browsers can help when handling errors.

Expand the stack

One way to handle exceptions is to add try...catch at the top of the call stack.

For example:

function main(bomb) {
 try {
  bomb();
 } catch (e) {
  // Handle all the error things
 }
}
Copy after login

However, browsers are event-driven, and exceptions in JavaScript are also events. When an exception occurs, the interpreter pauses execution and unwinds:

// scripts/errorHandlerDom.js
window.addEventListener('error', function (e) {
 var error = e.error;
 console.log(error);
});
Copy after login

This event handler catches any errors that occur in the execution context. Error events occurring on various targets can trigger various types of errors. This centralized error handling in the code is very aggressive. You can use daisy chaining to handle specific errors. If you follow SOLID principles, you can use error handling with a single purpose. These handlers can be registered at any time, and the interpreter will loop through the handlers that need to be executed. The code base can be released from the try...catch block, which also makes debugging easy. In JavaScript, it's important to treat error handling as event handling.

Capture stack

The call stack can be very useful when solving problems, and the browser can provide this information. Although stack attributes are not part of the standard, recent browsers can already view this information.

The following is an example of logging errors on the server:

// scripts/errorAjaxHandlerDom.js
window.addEventListener('error', function (e) {
 var stack = e.error.stack;
 var message = e.error.toString();
 if (stack) {
  message += '\n' + stack;
 }
 var xhr = new XMLHttpRequest();
 xhr.open('POST', '/log', true);
 // Fire an Ajax request with error details
 xhr.send(message);
});
Copy after login

Each error handling has a single purpose, which maintains the DRY principle of the code (single purpose, don’t repeat yourself principle).

In the browser, event handling needs to be added to the DOM. This means that if you are building a third-party library, your events will coexist with the client code. window.addEventListener() will handle it for you without erasing existing events.

This is a screenshot of the log on the server:

可以通过命令提示符查看日志,但是Windows上,日志是非动态的。

通过日志可以清楚的看到,具体什么情况触发了什么错误。在调试时调用堆栈也会非常有用,所以不要低估调用堆栈的作用。

在JavaScript中,错误信息仅适用于单个域。因为在使用来自不用域的脚本时,将会看不到任何错误详细信息。

一种解决方案是重新抛出错误,同时保留错误消息:

一旦重新启动了错误备

try {
 return fn();
} catch (e) {
 throw new Error(e.message);
}
Copy after login

份,全局错误处理程序就会完成其余的工作。确保你的错误处理处在相同域中,这样会保留原始消息,堆栈和自定义错误对象。

异步处理

JavaScript在运行异步代码时,进行下面的异常处理,会产生一个问题:

// scripts/asyncHandler.js
function asyncHandler(fn) {
 try {
  // This rips the potential bomb from the current context
  setTimeout(function () {
   fn();
  }, 1);
 } catch (e) { }
}
Copy after login

通过单元测试来查看问题:

// tests/scripts/asyncHandlerTest.js
it('does not catch exceptions with errors', function () {
 // The bomb
 var fn = function () {
  throw new TypeError('type error');
 };
 // Check that the exception is not caught
 should.doesNotThrow(function () {
  asyncHandler(fn);
 });
});
Copy after login

这个异常没有被捕获,我们通过单元测试来验证。尽管代码包含了try...catch,但是try...catch语句只能在单个执行上下文中工作。当异常被抛出时,解释器已经脱离了try...catch,所以异常未被处理。Ajax调用也会发生同样的情况。

所以,一种解决方案是在异步回调中捕获异常:

setTimeout(function () {
 try {
  fn();
 } catch (e) {
  // Handle this async error
 }
}, 1);
Copy after login

这种做法会比较奏效,但仍有很大的改进空间。

首先,这些try...catch block在整个区域纠缠不清。事实上,V8浏览器引擎不鼓励在函数内使用try ... catch block。V8是Chrome浏览器和Node中使用的JavaScript引擎。一种做法是将try...catch block移动到调用堆栈的顶部,但这却不适用于异步代码编程。

由于全局错误处理可以在任何上下文中执行,所以如果为错误处理添加一个窗口对象,那么就能保证代码的DRY和SOLID原则。同时全局错误处理也能保证你的异步代码很干净。

以下是该异常处理在服务器上的报告内容。请注意,输出内容会根据浏览器的不同而不同。

从错误处理中可以看到,错误来自于异步代码的setTimeout( )功能。

结论

在进行错误处理时,不要隐藏问题,而应该及时发现问题,并采用各种方法追溯问题的根源以便解决问题。虽然编写代码时,时常难免会埋下错误,但是我们也无须为错误的发生过于感到羞愧,及时解决发现问题从而避免更大的问题发生,正是我们现在需要做的。

相关推荐:

jQuery出错与解决方法小结

The above is the detailed content of How to handle errors 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

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

See all articles