Custom Errors in JavaScript: Extending Error

Custom Errors in JavaScript: Extending Error

Custom Errors in JavaScript: Extending Error

JavaScript allows you to create custom error classes by extending the built-in Error class. This helps categorize different types of errors in your application.

šŸ”¹ Why Use Custom Errors?

✅ Provides more meaningful error messages
✅ Helps with better error handling
✅ Allows catching specific error types

šŸ”¹ Creating a Custom Error Class

To create a custom error, extend the Error class and set a meaningful name property.

Example: Custom Validation Error

class ValidationError extends Error { constructor(message) { super(message); // Call parent constructor (Error) this.name = "ValidationError"; // Set the error name } } try { throw new ValidationError("Invalid email format"); } catch (error) { console.log(`${error.name}: ${error.message}`); // ✅ Output: ValidationError: Invalid email format }

super(message) calls the Error constructor to store the message.
✔ Setting this.name = "ValidationError" helps identify the error type.

šŸ”¹ Catching Specific Errors

You can use instanceof to handle different error types separately.

class ValidationError extends Error { constructor(message) { super(message); this.name = "ValidationError"; } } class DatabaseError extends Error { constructor(message) { super(message); this.name = "DatabaseError"; } } try { throw new DatabaseError("Connection failed"); } catch (error) { if (error instanceof ValidationError) { console.log("Handle validation issue:", error.message); } else if (error instanceof DatabaseError) { console.log("Handle database issue:", error.message); } else { console.log("General error:", error.message); } }

Output:

Handle database issue: Connection failed

✔️ Different error types are handled appropriately.

šŸ”¹ Adding Custom Properties

You can add extra properties to store additional information.

Example: Custom Error with Extra Info

class ApiError extends Error { constructor(message, statusCode) { super(message); this.name = "ApiError"; this.statusCode = statusCode; } } try { throw new ApiError("Not Found", 404); } catch (error) { console.log(`${error.name} (${error.statusCode}): ${error.message}`); // ✅ Output: ApiError (404): Not Found }

✔️ Useful for API responses when handling HTTP errors.

šŸ”¹ Reusing Custom Errors in Functions

Custom errors can be used in functions to enforce rules.

function checkAge(age) { if (age < 18) { throw new ValidationError("You must be 18 or older."); } return "Access granted!"; } try { console.log(checkAge(16)); // ❌ This will throw an error } catch (error) { console.log(`Error: ${error.message}`); }

Output:

Error: You must be 18 or older.

✔ Custom errors improve readability and debugging.

šŸ”¹ Summary

Extend Error to create custom errors
✔ Use meaningful error names (this.name)
✔ Catch errors specifically using instanceof
✔ Add extra properties for more details

šŸš€ Need more help? Let me know! 😊

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close