Capturing and Handling Frontend Exceptions
This article explains common frontend exceptions such as UI glitches, script errors, and network failures, classifies JavaScript error types, demonstrates handling techniques using try‑catch, finally, window.onerror, event listeners, Promise rejection handling, and framework‑specific solutions like React error boundaries, Vue errorHandler, and Axios interceptors.
Frontend developers often encounter exceptions that degrade user experience, such as unclickable buttons, missing elements, page freezes, and white screens. Understanding and handling these exceptions is essential for building robust web applications.
1. Introduction
An exception is an unexpected event that disrupts normal program execution. While frontend exceptions rarely crash the entire browser, they can block user interactions and must be addressed.
2. Exception Classification
JavaScript defines several built‑in error types, each with a message property supported across browsers. The ECMA‑262 specification lists seven primary error constructors:
Error – base class for all errors
EvalError – errors from eval()
RangeError – numeric range errors (e.g., array out‑of‑bounds)
ReferenceError – accessing undefined variables
SyntaxError – code parsing errors
TypeError – invalid type operations
URIError – malformed URI handling
3. Exception Handling
The standard way to catch synchronous errors is the try…catch statement, similar to Java:
try {
// code that may throw
} catch (error) {
// handle the error
}The optional finally block runs regardless of whether an error occurred:
function testFinally() {
try {
return "go out";
} catch (e) {
return "watch TV";
} finally {
return "do homework"; // this overrides previous returns
}
return "sleep";
}Note that try…catch cannot capture asynchronous errors.
3.1 Synchronous Errors
Example of a TypeError caused by accessing a missing property:
class People {
constructor(name) { this.name = name; }
sing() {}
}
const xiaoming = new People("小明");
xiaoming.dance(); // throws TypeError
xiaoming.girlfriend.name; // throws TypeErrorThese can be caught with try…catch :
try {
xiaoming.girlfriend.name;
} catch (error) {
console.log(xiaoming.name + " has no girlfriend", error);
}3.2 Syntax Errors
Syntax errors (e.g., using a Chinese semicolon) are detected at parse time and cannot be caught with try…catch :
try {
xiaoming.girlfriend.name; // invalid token
} catch (error) {
console.log(error);
}3.3 Asynchronous Errors
Errors thrown inside setTimeout or other async callbacks are not caught by surrounding try…catch :
try {
setTimeout(() => {
undefined.map(v => v);
}, 1000);
} catch (e) {
console.log("caught", e);
}
// Uncaught TypeError4. Global Exception Capture
4.1 window.onerror
For synchronous script errors, window.onerror receives an ErrorEvent :
window.onerror = function(message, source, lineno, colno, error) {
console.log("Captured error:", { message, source, lineno, colno, error });
};4.2 Static Resource Loading Errors
Use the onerror attribute or addEventListener('error', …, true) to capture failures of scripts, stylesheets, or images.
4.3 Promise Rejections
Unhandled promise rejections trigger the unhandledrejection event:
window.addEventListener("unhandledrejection", function(e) {
e.preventDefault();
console.log("Promise error caught", e.reason, e.promise);
});4.4 Framework‑Specific Handlers
React provides error boundaries via componentDidCatch :
class ErrorBoundary extends React.Component {
constructor(props) { super(props); this.state = { hasError: false }; }
componentDidCatch(error, info) {
this.setState({ hasError: true });
logErrorToMyService(error, info);
}
render() {
if (this.state.hasError) return
Something went wrong.
;
return this.props.children;
}
}Vue can set a global error handler:
Vue.config.errorHandler = (err, vm, info) => {
console.error("Vue error:", err, vm, info);
};Axios interceptors allow unified handling of HTTP errors such as 401 or 502:
axios.interceptors.response.use(
response => response,
error => {
if (error.response.status === 401) {
goLogin(); // redirect to login page
} else if (error.response.status === 502) {
alert(error.response.data.message || "System upgrading, try later");
}
return Promise.reject(error.response);
}
);5. Error Reporting
Even with thorough testing, production issues still arise. Integrating a monitoring service (e.g., Sentry) enables automatic collection of error details, user context, and stack traces, allowing rapid diagnosis and remediation.
6. Conclusion
Frontend exceptions can be grouped into seven categories; handling them requires distinguishing fatal from non‑fatal errors, adding try‑catch where appropriate, employing global listeners ( window.onerror , addEventListener('error') , unhandledrejection ), leveraging framework‑specific mechanisms, and centralizing reporting through tools like Sentry.
政采云技术
ZCY Technology Team (Zero), based in Hangzhou, is a growth-oriented team passionate about technology and craftsmanship. With around 500 members, we are building comprehensive engineering, project management, and talent development systems. We are committed to innovation and creating a cloud service ecosystem for government and enterprise procurement. We look forward to your joining us.
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.