Skip to content

Instantly share code, notes, and snippets.

@sergio-august
Created November 27, 2020 16:46
Show Gist options
  • Save sergio-august/a1c073b2da0beec8761f27866b1dae14 to your computer and use it in GitHub Desktop.
Save sergio-august/a1c073b2da0beec8761f27866b1dae14 to your computer and use it in GitHub Desktop.
Better error handling in Express with HttpException classes (CommonJS version)
/* eslint-disable require-jsdoc */
/**
* All specific http exceptions should inherit this class
*/
class HttpException extends Error {
/**
*
* @param {number} status HTTP status code
* @param {string} message Error message
*/
constructor(status, message) {
super(message);
this.status = status;
this.name = "HttpError";
}
}
/**
* 400 Bad request
*/
class HttpBadRequestException extends HttpException {
constructor(message = "Incorrect request") {
super(400, message);
this.name = "HttpBadRequestError";
}
}
/**
* 401 Unauthorized
*/
class HttpUnauthorizedException extends HttpException {
constructor(message = "Not authorized") {
super(401, message);
this.name = "HttpUnauthorizedError";
}
}
/**
* 403 Forbidden
*/
class HttpForbiddenException extends HttpException {
constructor(message = "Forbidden") {
super(403, message);
this.name = "HttpForbiddenError";
}
}
/**
* 404 NotFound
*/
class HttpNotFoundException extends HttpException {
constructor(message = "Not found") {
super(404, message);
this.name = "HttpNotFoundError";
}
}
module.exports = {
HttpException,
HttpBadRequestException,
HttpUnauthorizedException,
HttpForbiddenException,
HttpNotFoundException,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment