In this chapter, we will learn about creating custom error types in JavaScript. Custom error types allow you to define specific errors that are relevant to your application, making error handling more meaningful and manageable. We will cover:
- What are Custom Error Types?
- Creating Custom Error Types
- Using Custom Error Types
- Simple Programs using Custom Error Types
What are Custom Error Types?
Custom error types are user-defined error classes that extend the built-in Error
class. They provide a way to create specific error types for different error conditions, allowing for more precise error handling.
Creating Custom Error Types
To create a custom error type, you need to extend the Error
class and set the name
property to the name of your custom error.
Syntax
class CustomError extends Error { constructor(message) { super(message); this.name = "CustomError"; } }
Example
class ValidationError extends Error { constructor(message) { super(message); this.name = "ValidationError"; } } throw new ValidationError("Invalid input");
Using Custom Error Types
Custom error types can be used with try...catch
blocks to handle specific error conditions more effectively.
Example
class ValidationError extends Error { constructor(message) { super(message); this.name = "ValidationError"; } } function validateAge(age) { if (isNaN(age)) { throw new ValidationError("Age must be a number."); } if (age < 0 || age > 120) { throw new ValidationError("Age must be between 0 and 120."); } return "Valid age: " + age; } try { let userAge = validateAge(25); console.log(userAge); userAge = validateAge(-5); // This should trigger an error } catch (error) { if (error instanceof ValidationError) { console.log(`Validation error: ${error.message}`); } else { console.log(`Other error: ${error.message}`); } }
Output:
Valid age: 25 Validation error: Age must be between 0 and 120.
Simple Programs using Custom Error Types
Program 1: Custom Error for Division by Zero
class DivisionByZeroError extends Error { constructor(message) { super(message); this.name = "DivisionByZeroError"; } } function divide(a, b) { if (b === 0) { throw new DivisionByZeroError("Division by zero is not allowed."); } return a / b; } try { let result = divide(10, 2); console.log(result); result = divide(10, 0); // This should trigger an error } catch (error) { if (error instanceof DivisionByZeroError) { console.log(`Custom error: ${error.message}`); } else { console.log(`Other error: ${error.message}`); } }
Output:
5 Custom error: Division by zero is not allowed.
Program 2: Custom Error for Invalid JSON
class JSONParseError extends Error { constructor(message) { super(message); this.name = "JSONParseError"; } } function parseJSON(jsonString) { try { let data = JSON.parse(jsonString); console.log("Parsed JSON:", data); } catch (error) { throw new JSONParseError("Invalid JSON string"); } } try { let jsonString = '{"name": "Ramesh", "age": 25}'; parseJSON(jsonString); jsonString = '{"name": "Ramesh", "age": 25'; // This should trigger an error parseJSON(jsonString); } catch (error) { if (error instanceof JSONParseError) { console.log(`Custom error: ${error.message}`); } else { console.log(`Other error: ${error.message}`); } }
Output:
Parsed JSON: { name: 'Ramesh', age: 25 } Custom error: Invalid JSON string
Conclusion
In this chapter, you learned about creating and using custom error types in JavaScript. Custom error types allow you to define specific errors that are relevant to your application, making error handling more meaningful and manageable. We also provided various use cases with simple programs to demonstrate the usage of custom error types.