Reputation: 306
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.
Upvotes: 4
Views: 1263
Reputation: 1075587
You have two problems:
You're not exporting the classes. You're exporting a function that would create the classes if you called it, but then would throw them away because it doesn't do anything with them.
You're not doing anything with the result of require('../apiErrors');
To fix #1, either:
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;
}
};
module.exports = {
UnauthorizedError,
NotFoundError,
BadRequestError
};
or
module.exports.UnauthorizedError = class UnauthorizedError extends Error {
constructor(message) {
super(message);
this.name = 'UnauthorizedError';
this.code = 403;
}
};
module.exports.NotFoundError = class NotFoundError extends Error {
constructor(message) {
super(message);
this.name = 'NotFoundError';
this.code = 404;
}
};
module.exports.BadRequestError = class BadRequestError extends Error {
constructor(message) {
super(message);
this.name = 'BadRequestError';
this.code = 400;
}
}
To fix #2, in your example where you're just using BadRequestError
:
const { BadRequestError } = require('../apiErrors');
or
const BadRequestError = require('../apiErrors').BadRequestError;
or
const ErrorClasses = require('../apiErrors');
// ...then to use one of them...
throw new ErrorClasses.BadRequestError('Request is not good');
Upvotes: 6