w3resource

Custom TypeScript Validation Errors

TypeScript Error Handling : Exercise-5 with Solution

Write a custom TypeScript error class called `ValidationException` that extends the built-in `Error` class. Use this custom error class to throw and catch validation errors with custom error messages.

Sample Solution:

TypeScript Code:

class ValidationException extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'ValidationException';
  }
}

// Example usage:
function validateAge(age: number): void {
  if (age < 18) {
    throw new ValidationException('Age must be 18 or older.');
  }
}

try {
  const userAge = 12; // Change the age to test validation
  validateAge(userAge);
  console.log('Validation passed.');
} catch (error) {
  if (error instanceof ValidationException) {
    console.error(`Validation Error: ${error.message}`);
  } else {
    console.error(`Unexpected Error: ${error.message}`);
  }
}

Explanations:

In the exercise above -

  • First, define a custom error class called "ValidationException" that extends the built-in "Error" class. It takes a custom error message as a parameter and sets the error name.
  • Inside the "validateAge()" function, we check if the provided age is less than 18 and throw a 'ValidationException' with a custom error message if validation fails.
  • In the try-catch block, we call the 'validateAge' function with a user's age. If validation fails, we catch the 'ValidationException', display the custom error message, and handle it accordingly. If another unexpected error occurs, we catch it as well and display a generic error message.

Output:

Unexpected Error: Age must be 18 or older

TypeScript Editor:

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


Previous: TypeScript file Handling with Error Catching.
Next: TypeScript API Error Handling with custom class.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/typescript-exercises/typescript-error-handling-exercise-5.php