Click on theClick to subscribe to the column of Cloud Recommendation Guru, get the official recommended boutique content, learn technology not lost!

Robustness is the ability of a program to operate properly after encountering input, errors, or exceptions that are not included in the specification. In short, robust code is adaptable and doesn’t crash because of some exception.

Unrobust front-end code is shown as follows:

  • The interface returns an exception or error message, and the page goes blank.
  • When users perform some unconventional operations, the page goes blank.

How to write robust front-end code


To write robust front-end code, you need to handle input, errors, and exceptions outside the specification. Specifically, there are four points:

  1. Exception handling.
  2. Input check.
  3. Writing method optimization.
  4. Third party library selection.

Now, let’s be specific.

1. Exception handling

If you do not handle exceptions, the function may fail or the page may go blank. Exception handling can be divided into the following situations.

Actively catch runtime exceptions

Use try-catch to catch runtime errors in synchronized code. If it is asynchronous code, convert to await. Such as:

Try {doSth() await doSth2()} catch (e) {// handle exception}Copy the code

Handle unexpected global runtime exceptions

The Window raises error events when unhandled JavaScript runtime errors (including syntax errors) occur. Deal with it like this:

Window.addeventlistener ('error', (e) => {/* handle exception */})Copy the code

When a resource (such as or

const img = new Image(); Img. addEventListener('error', (e) => {/* handle exception */}) img. SRC = 'XXX'Copy the code

Asynchronous code: Processing of Promise Reject

When a Promise is rejected, it can be processed in the second argument to then or catch. Such as:

p().then(onSuccess, onReject)
p().catch(onReject)
Copy the code

If the Promise Reject is not handled, the window will fire the unHandledrejection event. Can be handled uniformly:

Window.addeventlistener ('unhandledrejection', (e) => {/* handle exceptions */})Copy the code

Common handling of interface errors when using Axios

Common handling of interface errors can be added to the interceptor returned by the Axios interface. Such as:

axios.interceptors.response.use(function (response) { return response; }, err => {// Error handling if(err.response) {switch (err.response.status) {case 400: err.message = 'Request error (400)'; break; Case 500: err.message = 'Server error (500)'; break; / /... } } return Promise.reject(error); })Copy the code

Exception handling of Vue

App.config. errorHandler = (err, VM, info) => {// Handle exceptions}Copy the code

React exception handling

React’s life cycle function ComponentDidCatch catches exceptions for child components. Therefore, a component can be wrapped around the root component to handle errors. Such as:

Class ErrorBoundary extends React.Component {componentDidCatch(error, info) {// Handle exception}}Copy the code

Use:

<ErrorBoundary>
  <App />
</ErrorBoundary>
Copy the code

2 Input Check

When input does not meet the criteria, return as soon as possible or actively report an error. The inputs include: interface return results, function parameters, component properties, and so on.

Interface return format check

The return of the interface is inconsistent with what the front end expects. The reasons may be:

  • The result returned by the interface changes without notifying the front end.
  • Some special request parameters cause the interface to return different values than expected.

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

const res = await fetchList()
const list = res.map(...)
Copy the code

If the interface returns something other than an array, the program will report an error. Optimizations like this can be made:

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

Function parameter check

JavaScript is a weakly typed language, and functions can take any parameter or no parameter. Therefore, without checking function parameters, there will be some inconsistencies as expected. For example, we want 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' Not as expectedCopy the code

To check the function parameters, you can optimize them as follows:

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

TypeScript is recommended. You can use it to check function arguments. 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)
}
Copy the code

Component Property Checking

Checking component properties is similar to checking function parameters, so I won’t go into details.

3. Writing optimization

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

1 All switches require default to handle exceptions or default situations.

Make a judgment call before accessing an object or array

A.B.C., a.&&A.b.C. If you’re using TypeScript, you could say: A? .b? C.

4 Third-party library selection

With a third library, you can reduce the number of wheels being built, thus improving development efficiency. But if third-party packages aren’t robust, the functionality that uses them isn’t robust either.

Robust third-party libraries are mature and stable. It is best not to select third-party libraries when:

  • It just came out.
  • There’s no stable version yet. If the library follows the semantic version specification, major version 0 is not stable.
  • The number of users is small. Low downloads, low star count.
  • There are no code tests.

Testing methods for robustness


Monkey tests can be used to test the robustness of your code.

The Money Test is also known as the monkey Test. In software testing, testers can perform a variety of bizarre operation patterns to test the robustness of the software.

A monkey test tool for browsers is recommended: grelins. Js. The tool does a random dot on the page to be tested. As shown below:

The next step in improving code quality


The next step in improving code quality is to improve code readability. I’ll cover that in my next article.

Jin Weiqiang recommended previous wonderful articles:

Talk about code quality – The introduction to Learn and Copy how to Improve Front-end Code Quality

Code Quality Layer 5 – just the functionality is implemented

“Cloud recommendation” is Tencent cloud plus community high-quality content column. Yunjianguan specially invites the top performers in the industry, focusing on the landing of cutting-edge technology and theoretical practice, to continue to interpret hot technologies in the cloud era and explore new opportunities for industry development.Click one button to subscribe, we will regularly push high-quality content for you.