Error Handling and Debugging · Lesson 29 of 40
Custom Errors and Async Error Handling
As an app grows, "something went wrong" isn't enough. You want to tell a validation problem from a missing record from a server outage – and show the user the right message for each. Custom error classes make that easy, and a few patterns make sure no async error goes unnoticed.
In this lesson
- Custom error classes with extra data
- Handling errors by type
- Errors in promises and async functions
- Global handlers for anything that slips through
Custom error classes
class AppError extends Error {
constructor(message, options) {
super(message, options);
this.name = this.constructor.name; // "ValidationError", "NotFoundError"…
}
}
class ValidationError extends AppError {
constructor(field, message) {
super(message);
this.field = field;
}
}
class NotFoundError extends AppError {
constructor(resource, id) {
super(`${resource} ${id} not found`);
this.status = 404;
}
}
const err = new ValidationError("email", "Enter a valid email");
console.log(err.name, err.field, err.message);
console.log(err instanceof ValidationError, err instanceof AppError, err instanceof Error);
ValidationError email Enter a valid email true true true
An error hierarchy
- Errorbuilt in: name, message, stack, cause
- AppErroryour base class – sets name automatically
- ValidationError · NotFoundError · AuthErrorspecific cases with extra fields
Handling errors by type
class AppError extends Error {
constructor(msg) { super(msg); this.name = this.constructor.name; }
}
class ValidationError extends AppError {
constructor(field, msg) { super(msg); this.field = field; }
}
class NotFoundError extends AppError {}
function registerUser({ email, age }) {
if (!email?.includes("@")) throw new ValidationError("email", "Enter a valid email");
if (age < 18) throw new ValidationError("age", "You must be 18 or older");
if (email === "ghost@example.com") throw new NotFoundError("Invite not found");
return `Welcome, ${email}`;
}
function handle(data) {
try {
return registerUser(data);
} catch (err) {
if (err instanceof ValidationError) return `Fix the ${err.field} field: ${err.message}`;
if (err instanceof NotFoundError) return `Sorry – ${err.message}`;
throw err; // unknown errors bubble up
}
}
console.log(handle({ email: "asha@example.com", age: 22 }));
console.log(handle({ email: "asha", age: 22 }));
console.log(handle({ email: "kid@example.com", age: 15 }));
console.log(handle({ email: "ghost@example.com", age: 30 }));
Welcome, asha@example.com Fix the email field: Enter a valid email Fix the age field: You must be 18 or older Sorry – Invite not found
Errors in async code
const fetchUser = async (id) => {
await new Promise((r) => setTimeout(r, 10));
if (id !== 1) throw new Error(`User ${id} not found`);
return { id, name: "Asha" };
};
// 1. try/catch around await
try {
await fetchUser(2);
} catch (e) {
console.log("try/catch:", e.message);
}
// 2. .catch on the promise
await fetchUser(3).catch((e) => console.log(".catch:", e.message));
// 3. Without await, try/catch does NOT catch it
try {
fetchUser(4).catch(() => console.log("caught later by .catch, not by try"));
console.log("try block finished first");
} catch {
console.log("never runs");
}
await new Promise((r) => setTimeout(r, 30));
try/catch: User 2 not found .catch: User 3 not found try block finished first caught later by .catch, not by try
A result helper: no try/catch at every call
async function attempt(promise) {
try {
return [null, await promise];
} catch (err) {
return [err, null];
}
}
const getPrice = async (sku) => {
if (sku === "PEN") return 20;
throw new Error(`No price for ${sku}`);
};
const [err1, pen] = await attempt(getPrice("PEN"));
const [err2, bag] = await attempt(getPrice("BAG"));
console.log(err1, pen);
console.log(err2.message, bag);
null 20 No price for BAG null
Global safety nets
Some errors will always slip through. Catch them globally to log them and show a friendly message – but treat these handlers as a last resort, not a replacement for local handling.
// Browser
window.addEventListener("error", (event) => {
reportToServer({ message: event.message, stack: event.error?.stack });
});
window.addEventListener("unhandledrejection", (event) => {
reportToServer({ message: String(event.reason) });
showToast("Something went wrong. Please try again.");
});
// Node.js
process.on("unhandledRejection", (reason) => {
console.error("Unhandled rejection:", reason);
process.exitCode = 1;
});
Good error messages
- For users: say what happened and what to do next – "Payment failed. Your card was not charged; please try again."
- For developers: include context – IDs, inputs, the operation – and keep the original error as
cause. - Never show stack traces or internal details to users; log them instead.
Practice
Try it yourself
Create an
HttpErrorclass with astatus, and a function that returns "Please log in" for 401 and "Server problem" for 500+.Show solution
class HttpError extends Error { constructor(status) { super(`HTTP ${status}`); this.name = "HttpError"; this.status = status; } } const messageFor = (err) => err instanceof HttpError && err.status === 401 ? "Please log in" : err instanceof HttpError && err.status >= 500 ? "Server problem" : "Unexpected error"; console.log(messageFor(new HttpError(401)), "|", messageFor(new HttpError(503)), "|", messageFor(new Error("x")));Please log in | Server problem | Unexpected error
Quick check
Why set this.name in a custom error?
So logs and err.name show the specific type instead of "Error".
Will try/catch catch a rejected promise you didn't await?
No – the rejection happens later; await it or attach .catch.
Which browser event catches unhandled promise rejections?
unhandledrejection on window.
Summary
- Extend Error to create typed errors with extra fields; check them with instanceof.
- In async code, await inside try/catch or attach .catch – never leave a promise unhandled.
- Add global handlers as a safety net, and write messages that help users and developers.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.