How to Write Robust Front-End Code: Practices and Techniques
Writing robust front‑end code involves systematic exception handling, thorough input validation, disciplined code‑style practices such as default cases and optional chaining, careful selection of mature third‑party libraries, and proactive robustness testing like monkey testing to ensure the UI remains functional under unexpected conditions.
Robustness means that a program can continue to run correctly when it encounters inputs, errors, or exceptions that are outside the specification. In simple terms, robust code adapts well and does not crash due to unexpected situations.
Typical signs of non‑robust front‑end code include:
Page white‑screen when an API returns an error.
Page white‑screen when a user performs unconventional actions.
How to write robust front‑end code – focus on four aspects:
Exception handling.
Input validation.
Code style optimization.
Choosing reliable third‑party libraries.
1. Exception handling
Use try‑catch for synchronous code and convert asynchronous code to await style:
try {
doSth()
await doSth2()
} catch (e) {
// handle exception
}Handle unexpected global runtime errors via the error event:
window.addEventListener('error', (e) => { /* handle error */ })Handle resource loading failures (e.g., <img> or <script> ) similarly:
const img = new Image();
img.addEventListener('error', (e) => { /* handle error */ });
img.src = 'xxx';For unhandled Promise rejections, listen to unhandledrejection :
window.addEventListener('unhandledrejection', (e) => { /* handle rejection */ })Axios error handling can be centralized in a response interceptor:
axios.interceptors.response.use(function (response) {
return response;
}, err => {
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(err);
});Vue global error handling:
app.config.errorHandler = (err, vm, info) => {
// handle error
}React error boundaries:
class ErrorBoundary extends React.Component {
componentDidCatch(error, info) {
// handle error
}
}Usage:
<ErrorBoundary>
<App />
</ErrorBoundary>2. Input validation
Validate API responses, function parameters, and component props early.
API response format check – ensure the data type matches expectations:
const res = await fetchList();
const list = Array.isArray(res) ? res.map(...) : [];Function parameter validation – guard against missing or wrong‑type arguments:
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 can enforce parameter types directly:
function sum(a: number | string, b: number | string) {
return parseFloat(a as string) + parseFloat(b as string);
}Component prop validation follows the same principle and can be expressed with PropTypes or TypeScript interfaces.
3. Code style optimization
Always provide a default case in switch statements to handle unexpected values.
Guard object or array access with logical AND or optional chaining (e.g., a && a.b && a.b.c or a?.b?.c ).
4. Choosing third‑party libraries
A robust third‑party library should be mature and stable. Avoid libraries that:
Are newly released.
Have no stable version (major version 0 according to semantic versioning).
Have very few users or stars.
Lack automated tests.
5. Testing robustness
Monkey testing (also called “Money Test” or “chaos testing”) can reveal hidden fragilities by performing random, unexpected actions on the UI. A popular tool for browser‑based monkey testing is gremlins.js , which injects random events into the page.
6. Next steps
The next article will discuss improving code readability, which further enhances overall code quality.
Tencent Cloud Developer
Official Tencent Cloud community account that brings together developers, shares practical tech insights, and fosters an influential tech exchange community.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.