JavaScript
Error Handling
Error handling in JavaScript provides control over unforeseen situations during code execution.
It uses
try...catch...finallystructures, error objects (Error), and the ability to create custom error types.
Error Handling Basics
- The
try...catchstructure catches exceptions thrown withthrow. - The
finallyblock always executes — regardless of whether there was an error.
try {
const data = JSON.parse("invalid json");
} catch (err) {
console.error("Parsing error:", err.message);
} finally {
console.log("Completed");
}If an error is not caught, code execution is interrupted and an exception is thrown in the call stack.
Error Object
- A built-in error type containing standard properties:
name— the name of the error (Error,TypeError,ReferenceError, etc.);message— error description;stack— call trace (for debugging).
throw new Error("Something went wrong");Asynchronous Errors
- In
async/awaitstructures, errors are handled viatry...catcharoundawait. - For
Promise,.catch()orPromise.allSettled()are used.
async function fetchData() {
try {
const res = await fetch("/api");
const data = await res.json();
return data;
} catch (err) {
console.error("Request error:", err);
}
}An error inside a promise is not caught by an external try...catch unless await is used.
Creating Custom Error Types
- You can extend the base
Errorclass to create custom errors with a meaningful name.
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
throw new ValidationError("Invalid input data");This approach makes it easier to distinguish between error types during debugging and logging.
Practical Recommendations
- Use specific error types (
TypeError,SyntaxError,RangeError) instead of a generalError. - Always add
.catch()ortry...catchin asynchronous code. - Do not suppress errors unnecessarily — log them or throw them higher (
throw err). - Use global handlers (
window.onerror,unhandledrejection) for monitoring.
Key Ideas
try...catchprotects execution from unpredictable crashes.- Errors can be caught synchronously and asynchronously (
Promise,async/await). - Custom error classes make code clear and safe.
- Proper error handling improves the reliability and UX of the application.