class AppError extends Error{
constructor(message,statusCode){
super(message)
this.statusCode = statusCode
}
}
AND
class AppError extends Error{
constructor(message,statusCode){
super(message)
this.message=message
this.statusCode = statusCode
}
}
AND
class AppError{
constructor(message,statusCode){
this.message = message
this.statusCode = statusCode
}
}
I am woking on nodeJs project using mongo.During error handling I created this class but not understading difference between these.AND which is best way? does it matter if I extend to error class or not and direct assign message property? Most importantly. When I print object created using 1st class, why message property is missing ? Though when I print it explicitly (for eg. err.message) value is shown
CodePudding user response:
class Error {
constructor(message) {
this.message = message
}
}
class AppError extends Error{
constructor(message,statusCode){
super(message) // This calls the constructor of the parent
this.statusCode = statusCode
}
}
// AND
class AppError extends Error{
constructor(message,statusCode){
super(message) // This calls the parent constructor
this.message=message // This ovverrides the previous line
this.statusCode = statusCode
}
}
// AND
class AppError{
constructor(message,statusCode){
this.message = message // This is just without the extended class
this.statusCode = statusCode
}
}
Another example: This shows you that the parent constructor is called, but you are missing chicken and food
class Error {
constructor(message, chicken, food) {
this.message = message
this.chicken = chicken
this.food = food
}
}
class AppError extends Error {
constructor(message, statusCode) {
super(message)
this.statusCode = statusCode
}
}
let x = new AppError("Message", "Errorcode")
console.log(x)
To reduce redundant code and you have a lots of class parameters it could look like this:
class Animal {
constructor(price, size, age) {
this.price = price
this.size = size
this.age = age
}
}
class Cat extends Animal {
constructor(cattype, price, size, age) {
super(price, size, age) // This is way shorter than repeating what is written in the Animal class
this.cattype = cattype
}
}
let x = new Cat("weirdtype", "500Euros", "BigSize", "OldAge")
console.log(x)
CodePudding user response:
- The class
AppError
extends (inherit) from theError
class - That means AppError's
this
context includes the properties and methods defined in the Error class, plus whatever properties and methodsAppError
defines for itself. - Call the
super(arguments)
in the child class constructor to invoke the parent class constructor
Let them know that no question is too small or too strange to be asked :)
Js is interesting try this book