7
Click "Cloud Recommendations" with one click, get the official recommended high-quality content, and learn technology without getting lost!

image.png

Robustness refers to the ability of a program to operate normally when encountering input, errors, and exceptions outside the specification. In short, robust code is highly adaptable and will not crash the program due to some exceptions.

Unrobust front-end code is reflected in:

When the interface returns an exception or reports an error, the page is blank.
When the user performs some unconventional operations, the page is blank.

How to write robust front-end code

To write robust front-end code, it is necessary to handle out-of-spec input, errors, and exceptions. Specifically, there are 4 points:

1. Exception handling.
2. Input check.
3. Writing optimization.
4. Selection of third-party libraries.

Below, we are specific.

1. Exception handling

If you do not handle exceptions, it will lead to functional errors in light, and white screen in heavy cases. Exception handling can be divided into the following situations.

Actively catches runtime exceptions
Use try-catch to catch runtime errors from synchronous code. If it is asynchronous code, it needs to be converted into await. like:

try {
  doSth()
  await doSth2()
} catch (e) {
  // 处理异常
}

Handling unexpected global runtime exceptions
When unhandled JavaScript runtime errors (including syntax errors) occur, the window fires the error event. Do it like this:

window.addEventListener(
  'error',
  (e) => {/* 处理异常 */}
)

When a resource (such as <img> or <script>) fails to load, the element that loads the resource fires the error event. Do it like this:

const img = new Image();
img.addEventListener(
  'error',
  (e) => {/* 处理异常 */}
)
img.src = 'xxx'

Asynchronous code: Promise reject handling
When a Promise is rejected, it can be handled in the second parameter of then or in catch. like:

p().then(onSuccess, onReject)
p().catch(onReject)

If the Promise reject is not handled, the window will trigger the unhandledrejection event. Can be unified to deal with:

window.addEventListener(
  'unhandledrejection',
  (e) => {/* 处理异常 */}
)

General handling of interface errors when using Axios
You can add general handling of interface errors to the interceptor returned by the Axios interface. For example:

axios.interceptors.response.use(function (response) {
  return response;
}, err => {
  // 报错处理
  if(err.response) {
    switch (err.response.status) {
      case 400: err.message = '请求错误(400)'; break;
      case 500: err.message = '服务器错误(500)'; break;
      // ...
    }
  }
  return Promise.reject(error);
})

Exception handling for

app.config.errorHandler = (err, vm, info) => {
  // 处理异常
}

Exception Handling for React
React's lifecycle function ComponentDidCatch can catch exceptions from child components. Therefore, it is possible to wrap a component around the root component to handle errors. like:

class ErrorBoundary extends React.Component {
  componentDidCatch(error, info) {
    // 处理异常
  }
}

use:

<ErrorBoundary>
  <App />
</ErrorBoundary>

2 Input check

When the input does not meet the conditions, it is necessary to return as soon as possible or actively report an error. The input here includes: the return result of the interface, the parameters of the function, the properties of the component, etc.

interface return format check
The return of the interface may be inconsistent with the front-end expectations. reasons may be:

The return result of the interface changes, but the front end is not notified.
Some special request parameters cause the return of the interface to be different from the expected value.

Therefore, we need to check the interface return format. Let's look at an example:

const res = await fetchList()
const list = res.map(...)

If the interface returns not an array, the program will report an error. You can do optimizations like this:

const res = await fetchList()
const list = Array.isArray(res) ? res.map(...) : []

Function parameter check
JavaScript is a weakly typed language, and the parameters of functions can pass arbitrary values or no parameters. Therefore, without checking function parameters, there will be some inconsistencies with expectations. For example, expect to implement the function of summing two numbers:

function sum (a, b) {
  return a + b
}

sum(3, 4) // 7。和预期一致
sum() // NaN。和预期不一致
sum('3', 4) // '34'。和预期不一致

Checking the function parameters can be optimized like this:

function sum (a, b) {
  if(isNaN(parseFloat(a)) || isNaN(parseFloat(b))) {
    throw 'param error. param should be a num'
  }
  return parseFloat(a) + parseFloat(b)
}

TypeScript is recommended. You can use it to check function parameters. The above code is written in TypeScript like this:

function sum (a: number | string, b: number | string) {
  return parseFloat(a as string) + parseFloat(b as string)
}

Component property check
The property check of the component is similar to the function parameter check, so I won't go into details.

3 Writing optimization

Many writing optimizations can improve code robustness. Here are 2 points.

1 switch needs to have default to handle exceptions or default cases.

2 Make judgments before accessing objects or arrays

For example: a.b.c changed to a && a.b && a.b.c . If you use TypeScript, you can write: a?.b?.c .

4 Choice of third-party libraries

Using the third library can reduce the number of wheels and improve development efficiency. But if the third-party package is not robust, the functions that use the third-party package are also not robust.

Robust third-party libraries are mature and stable. It is best not to choose third-party libraries for the following situations:

Just came out.
There is no stable version yet. If the library follows the Semantic version specification, no major version number 0 is stable.
Very few people use it. The number of downloads is low, and the number of stars is low.
There are no code tests.

Robustness testing method

You can use monkey testing to test the robustness of your code.

Monkey test (Money Test), also known as funny test. In software testing, testers can perform a variety of bizarre operating modes to test the robustness of the software.

Here is a monkey testing tool for browsers: gremlins.js. The tool will mess around with the page to be tested. As shown below:

image.png

The next step in improving code quality

The next step in improving code quality is improving code readability. I will cover it in the next article.

3金伟强.jpg

Jin Weiqiang's previous wonderful articles are recommended:

Talk about code quality - Preface
Code Quality Tier 5 - just implements functionality

213.png

"Cloud Recommendation" is a high-quality content column of Tencent Cloud Plus community. The cloud recommendation officer specially invites industry leaders to focus on the implementation of cutting-edge technologies and theoretical practice, and continue to interpret hot technologies in the cloud era and explore new opportunities for industry development. One-click subscription to , we will regularly push premium content for you.


腾讯云开发者
21.9k 声望17.3k 粉丝