- Courses
- 💻Programming Languages
- 🌐JavaScript
- Tooling and Performance
- Advanced Error Handling
On this page
Advanced Error Handling
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
In a professional production environment, an application’s quality is measured not just by its features, but by how it behaves when things go wrong. Basic error handling prevents crashes, but Advanced Error Handling provides the diagnostic data necessary to fix bugs quickly and the user experience necessary to keep clients informed. This lesson explores how to structure errors as first-class objects and manage the execution lifecycle using advanced control structures.
The Try, Catch, and Finally Lifecycle
The try...catch statement is the primary mechanism for handling exceptions. However, at an expert level, we must utilize the full lifecycle, including the finally block and conditional re-throwing.
- Try: Contains the "risky" code that might throw an exception.
- Catch: Executes only if an exception occurs. In modern JavaScript (ES2019+), you can omit the error parameter
catch { ... }if the error object itself isn’t needed. - Finally: Executes regardless of the outcome. This is the standard location for cleanup operations, such as closing database connections, clearing timers, or resetting "loading" states in a UI.
async function sensitiveOperation() {
showLoadingSpinner();
try {
const data = await fetchData();
process(data);
} catch (err) {
reportToSentry(err); // External logging
displayUserFriendlyMessage(err.message);
} finally {
hideLoadingSpinner(); // Always runs, preventing a stuck UI
}
}
Building Custom Error Classes
Standard JavaScript errors (like TypeError or ReferenceError) are often too generic for complex applications. By extending the built-in Error class, you can create domain-specific errors that carry extra metadata, such as HTTP status codes or internal error IDs.
Implementation of a Base Custom Error
Using super() is required to call the parent Error constructor, and Error.captureStackTrace is used to ensure the stack trace points to where the error was actually instantiated.
class AppError extends Error {
constructor(message, statusCode) {
super(message);
this.name = this.constructor.name;
this.statusCode = statusCode;
this.isOperational = true; // Distinguishes known app errors from system crashes
Error.captureStackTrace(this, this.constructor);
}
}
class ValidationError extends AppError {
constructor(message) {
super(message, 400);
}
}
Strategic Benefits
- Type Checking: You can use
instanceofin yourcatchblocks to handle different errors uniquely. - Metadata: You can attach specific details (like which form field failed validation) directly to the error object.
- Centralized Logging: Logging services can filter errors based on the
nameorisOperationalflags.
Rethrowing and Error Bubbling
Sometimes, a catch block shouldn't handle every error. If an error occurs that the local block doesn't recognize, it should be re-thrown to be handled by a more global error manager. This prevents "swallowing" critical bugs.
try {
parseJsonData(input);
} catch (err) {
if (err instanceof SyntaxError) {
handleMalformedJson();
} else {
throw err; // Bubbles up to the next catch block or global handler
}
}
Global Error Management
In large-scale applications, you should never rely solely on local try/catch. You need a "safety net" for errors that slip through.
window.onerror: Catches most uncaught synchronous errors.window.onunhandledrejection: Specifically catches Promises that were rejected without a.catch()block.
Expert Implementation Standards
To maintain a resilient codebase, follow these industry-standard rules:
- Never "Swallow" Errors: An empty
catch {}block is an anti-pattern. If you catch an error, you must either fix it, log it, or report it. - Throw Objects, Not Strings: Always use
throw new Error("msg")or a custom class. Throwing a plain stringthrow "Error"loses the stack trace, making debugging nearly impossible. - Distinguish Error Types: Use custom classes to separate Operational Errors (e.g., failed API call, invalid user input) from Programmer Errors (e.g., trying to read a property of
undefined). - Use Finally for Idempotency: Ensure that any state changes made at the start of an operation (like setting a flag to
true) are reverted in thefinallyblock to ensure the system remains in a predictable state.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Regular Expressions (Regex)
Next
Scalable Architecture
-
The Try, Catch, and Finally Lifecycle
-
Building Custom Error Classes
- Implementation of a Base Custom Error
- Strategic Benefits
-
Rethrowing and Error Bubbling
-
Global Error Management
-
Expert Implementation Standards
