I am working on an API and I am trying to manage errors in a clean way.
So I tried to define a module gathering all Error subclasses that I might want to throw in my API.
Those classes correspond to HTTP error codes that I'd like to return to the requester. I chose to put them in a module all by themselves because I will use them in several other modules as well.
I would like to use my Error subclasses like this:
require('../apiErrors');
function apiRequest(req, res) {
doRequest(req, function (err, data) {
if (err) {
throw new BadRequestError('Request is not good');
}
res.send(200, data);
})
}
And my module is defined like this: apiErrors.js
module.exports = () => {
class UnauthorizedError extends Error {
constructor(message) {
super(message);
this.name = 'UnauthorizedError';
this.code = 403;
}
}
class NotFoundError extends Error {
constructor(message) {
super(message);
this.name = 'NotFoundError';
this.code = 404;
}
}
class BadRequestError extends Error {
constructor(message) {
super(message);
this.name = 'BadRequestError';
this.code = 400;
}
}
};
The outcome of this is a ReferenceError: BadRequestError is not defined.
At this point I wonder if my way of doing it is indeed clean and what I am missing when exporting my apiErrors module.