w3resource

TypeScript input validation with custom class

TypeScript Error Handling : Exercise-8 with Solution

Write a TypeScript application that processes user input. Create a custom error class, `InputError`, to handle invalid input errors. Use this error class to validate user input and display appropriate error messages.

Sample Solution:

TypeScript Code:

// Custom error class for input errors
class InputError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'InputError';
  }
}

// Function to process user input and validate it
function processUserInput(input: string): void {
  if (!input) {
    throw new InputError('Input is required.');
  }

  if (input.length < 3) {
    throw new InputError('Input must be at least 3 characters long.');
  }

  console.log(`User input processed: ${input}`);
}

// Read user input (simulate user input)
const userInput = 'typescript'; // Change the input to test validation

try {
  processUserInput(userInput);
  console.log('Processing complete.');
} catch (error) {
  if (error instanceof InputError) {
    console.error(`Input Error: ${error.message}`);
  } else {
    console.error(`Unexpected Error: ${error.message}`);
  }
}

Explanations:

In the exercise above -

  • First, we define a custom error class called "InputError" that extends the built-in Error class. It takes a custom error message as a parameter and sets the error name.
  • The "processUserInput()" function processes user input and validates it. It checks if input is required and if its length is at least 3 characters. If validation fails, it throws an 'InputError' with a custom error message.
  • We simulate user input by setting the 'userInput' variable. You can change the value of 'userInput' to test different input scenarios.
  • In the try-catch block, we call the "processUserInput()" function with the user's input. If validation fails and an 'InputError' is caught, it displays the custom input error message. Otherwise, it handles other unexpected errors.

Output:

User input processed: typescript
Processing complete

TypeScript Editor:

See the Pen TypeScript by w3resource (@w3resource) on CodePen.


Previous: TypeScript Database Error Handling with custom class.
Next: TypeScript File Handling with error propagation.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.