custom error nodejs
Step 1: Define a new custom error class using the class
keyword and extend the Error
class.
Step 2: Inside the custom error class, use a constructor function to accept parameters and call the super
method with the error message.
Step 3: Customize the error class by adding any additional properties or methods that are required for your use case.
Step 4: You can then throw this custom error object in your Node.js application using throw
keyword wherever needed.
Example:
class CustomError extends Error {
constructor(message, errorCode) {
super(message);
this.name = this.constructor.name;
this.errorCode = errorCode;
}
getErrorCode() {
return this.errorCode;
}
}
// Throwing the custom error
function someFunction() {
throw new CustomError('Custom error message', 500);
}