DEV Community

Discussion on: Central Error Handling in Express

Collapse
 
maxiqboy profile image
Thinh Nguyen • Edited

Great Article, Thanks

btw, I got a small question in this own Error class :

class ErrorHandler extends Error {
  constructor(statusCode, message) {
    super();
    this.statusCode = statusCode;
    this.message = message;
  }
}
module.exports = {
  ErrorHandler
}
Enter fullscreen mode Exit fullscreen mode

Why we have to write like this (1)

super();
this.message = message;
Enter fullscreen mode Exit fullscreen mode

but not like this (2)

super(message);
Enter fullscreen mode Exit fullscreen mode

?

Actually, I wrote like (2) and then my own class lost a message property

It only comes back when I change it to (1).

What is the difference between them ?

Thanks,

Collapse
 
nedsoft profile image
Chinedu Orie • Edited

The super() method is used when a class (child) inherits from another class (parent).
The super() method provides a means of syncing the child's constructor to the parent's constructor.
Let me illustrate with an example

class Foor {
    constructor(name) {
        this.name = name
   }
    printName = () => {
      console.log(this.name);
   }
}

class Bar extends Foo {

     constructor(name) {
         super(name)
   }
}

const bar = new Bar('Test');

bar.printName() // Test
Enter fullscreen mode Exit fullscreen mode



Now, looking at the code above,
Foorequires anameto be passed to its constructor in order to function, whenBarinherited fromFoo, there's no way thenamecould be passed down toFooif not with thesuper()`

So, in relation to the snippet that you shared above, you are passing the message to the parent which in this case is Error, that way the child ErrorHandler has no access to message

I hope this helps.

Collapse
 
peacefulseeker profile image
Alexey Vorobyov

Is there a necessity in Bar constructor at all?
You just pass the same Test value to the parent class ultimately. In this case
there is no need to a constructor at all I assume and Eslint should also hint about it.