Summary - Error handling
Build a user sign-up flow with a custom error class and async error handling.
Summary - Error handling
In this group you learned to create custom error classes, propagate errors by wrapping them with cause and rethrowing, catch multiple patterns with instanceof, use async error strategies and handle errors globally.
Now you will combine all of these in a user sign-up flow: throwing a custom error, async registration and setting up a global handler.
Exercise Sign-up flow
Write an async function signUp. If the email parameter is empty, throw new ValidationError('Email required'). Then in a try block call await registerUser(email). In a catch (err) block call console.error(err).
Show example solution
async function signUp(email) {
if (!email) {
throw new ValidationError('Email required');
}
try {
await registerUser(email);
} catch (err) {
console.error(err);
}
}
Exercise Set up the global handler
Write a global error listener. With window.addEventListener('error', handler) send event.message to the reportError function. With window.addEventListener('unhandledrejection', handler) send event.reason to the reportError function.
Show example solution
window.addEventListener('error', (event) => {
reportError(event.message);
});
window.addEventListener('unhandledrejection', (event) => {
reportError(event.reason);
});
Test yourself
-
Match concepts to their definitions
- extends Error
- Custom error class
- throw err
- Error propagation
- instanceof
- Type check
- unhandledrejection
- Global catching
-
Error class skeleton
class AuthError ____ { constructor(message) { super(message); this.name = 'AuthError'; } }Show answer
class AuthError extends Error { constructor(message) { super(message); this.name = 'AuthError'; } } -
What happens when await rejects in an async function?
- The promise auto-fulfils
- It is silently ignored
- The error is caught by try/catch
- window.onload fires
Show answer
The error is caught by try/catch — Correct! An await rejection is caught by try/catch.