Blog>
Snippets

Extending Error for User Validation

Create a custom UserValidationError class that extends the native Error object, for use in a user management system when a user's input data fails to validate.
class UserValidationError extends Error {
  constructor(message) {
    super(message);
    this.name = 'UserValidationError';
  }
}
Defines a custom error class 'UserValidationError' that extends the built-in Error class, intended for user validation errors.
function validateUser(user) {
  if (!user.username) {
    throw new UserValidationError('Username is required.');
  }
  // Add more validation checks as needed
}
Function 'validateUser' shows how to use the custom UserValidationError. It throws an error if the username is missing.
try {
  validateUser({});
} catch (error) {
  if (error instanceof UserValidationError) {
    console.error('User validation error:', error.message);
  } else {
    console.error('Unknown error:', error);
  }
}
Demonstrates how to use a try/catch block to catch and handle the UserValidationError when calling the 'validateUser' function.