I tried creating a single file which contains error classes. This file is supposed to be the file required once someone need a custom error class which should be within catch
block.
The snippet looks like this
class FooError extends Error {
constructor() {
this.name = 'FooError';
}
}
class BarError extends Error {
constructor() {
this.name = 'BarError';
}
}
module.exports = FooError;
module.exports = BarError;
I'm supposed to use the error like this:
async function doSomething() {
const requestResult = await doRequest();
if (requestResult.error) {
const errorName = requestResult.error.name;
if (errorName === 'Foo') { throw new FooError('some error message #1'); }
if (errorName === 'Bar') { throw new BarError('some error message #2'); }
throw new Error('unhandled error');
}
return requestResult.data;
}
But then eslint complains that it's better to make 1 class per 1 file which is understandable as multiple classes with logics in it will clog it up in no time making its readability a disaster.
But then, if this error classes need 1 file for each, I feel this is an overkill. Not to mention maintaining these files 1 by 1 is not fun at all when there's like a lot of them in 1 folder.
Coming from ruby, I usually put these error classes together in 1 file, since it's just a 1-liner and rubocop seems to not complain about it either.
Any thought on this? I'm considering to disable the rules on this specific file, though I don't know if this is for the best
Will the readibility suffers from the perspective of others were I to do this?
If so, is there any better way to organize this in a better way without creating 1 file for each error class?
Thanks in advance.
I don't think having two files for two classes is overkill. I don't think size of class should even be a criteria to identify if a classes can be in one file or in separate.
Just imagine you need only one of the error message in another class. The way you want it will basically end up requiring the whole file while you only need one.
You could consider creating a folder for errors and have all your classes in separate file. Then have a index file which exports these classes.