I am learning "Error Handling in JavaScript" and read articles on site point. In the articles, it shows the way to make custom error type:
function DivisionByZeroError(message) {
this.name = "DivisionByZeroError";
this.message = (message || "");
}
DivisionByZeroError.prototype = new Error();
DivisionByZeroError.prototype.constructor = DivisionByZeroError;
However, I can not understand why the function constructor has to assign to itself again. That is,
DivisionByZeroError.prototype.constructor = DivisionByZeroError;
I think this is because DivisionByZeroError.prototype assigned to new Error() so the prototype was changed.
But I am not sure why even after commenting out that line. The code still works fine.
Demo code is put on jsfiddle
Reference:
Exceptional Exception Handling in JavaScript
A Guide to Proper Error Handling in JavaScript
newfor inheritance is horrible. Subclassing builtins likeErrorworks best with ES6class.