I was solving Circular Buffer today and had a hard time figuring out how to create custom exceptions. That is because I was expecting the matcher to match with a custom exception class, but what it actually does is matches with Error itself.
expect(()=>buffer.read()).toThrow(bufferEmptyException());
Note bufferEmptyException is a function call which gives no idea what its return type should be - Error/CustomError/String??
For custom exceptions in ES6, most sources say that this should suffice: (which is far better than its ES5 equivalent)
class bufferFullException extends Error {}
But it does not work since babel does not allow subclassing built-in classes (also mentioned in the docs). I ended up using the babel-plugin for allowing subclassing. Solution here.
Most other exercises just throw a String, while others like wordy and circular-buffer throw custom exceptions.
So I have two questions:
-
Should we have a standard way of doing exceptions in the track? Is throwing Strings OK or should we go all custom?
-
For the exercises that expect custom errors, is class bufferFullException extends Error {} better than what we have right now? which is:
const BufferFullException = () => ({
name: "buffer full exception!",
message: "can't write to a full buffer!"
});
I was solving
Circular Buffertoday and had a hard time figuring out how to create custom exceptions. That is because I was expecting the matcher to match with acustomexception class, but what it actually does is matches withErroritself.Note
bufferEmptyExceptionis a function call which gives no idea what its return type should be -Error/CustomError/String??For custom exceptions in ES6, most sources say that this should suffice: (which is far better than its ES5 equivalent)
But it does not work since babel does not allow subclassing built-in classes (also mentioned in the docs). I ended up using the babel-plugin for allowing subclassing. Solution here.
Most other exercises just throw a String, while others like
wordyandcircular-bufferthrow custom exceptions.So I have two questions:
Should we have a standard way of doing exceptions in the track? Is throwing Strings OK or should we go all custom?
For the exercises that expect custom errors, is
class bufferFullException extends Error {}better than what we have right now? which is: