About Lesson
Combining try…catch with Custom Errors
Custom errors and specific error types help create more meaningful error messages and workflows for users.
Example: User Login with Error Handling
Let’s say you’re validating a user’s login. You want to catch errors if the username or password is missing.
JavaScript
function loginUser(username, password) {
try {
if (!username) throw new ReferenceError("Username is required.");
if (!password) throw new ReferenceError("Password is required.");
if (password.length < 8) throw new Error("Password must be at least 8 characters.");
console.log("Login successful!");
} catch (error) {
console.log("Login Error:", error.message);
}
}
loginUser("", ""); // Login Error: Username is required.
loginUser("user", "pass"); // Login Error: Password must be at least 8 characters.
loginUser("user", "securepass"); // Login successful!
This example uses custom errors and ReferenceError for missing fields and checks for password length. This way, users get clear feedback about why login fails.