Skip to content

Instantly share code, notes, and snippets.

@danigb
Created April 6, 2018 10:48
Show Gist options
  • Save danigb/9774132dc2986d6335b3139dd02a5f3d to your computer and use it in GitHub Desktop.
Save danigb/9774132dc2986d6335b3139dd02a5f3d to your computer and use it in GitHub Desktop.
Custom API Errors
'use strict'
const httpStatus = require("http-status");
/**
* Extends the node base Error object to have status while capturing the stack trace
*/
class ApiError extends Error {
constructor(statusCode = 500, message = httpStatus[statusCode]) {
super(message);
this.name = this.constructor.name;
Error.captureStackTrace(this, this.constructor);
this.status = statusCode;
}
};
/**
* 400 BAD REQUEST
* The server cannot or will not process the request due to
* something that is perceived to be a client error
*/
const BadRequestError = message => new ApiError(400)
/**
* 401 UNAUTHORIZED
* The request has not been applied because it lacks valid authentication
* credentials for the target resource.
*/
const UnauthorizedError = message => new ApiError(401)
/**
* 403 FORBIDDEN
* The server understood the request but refuses to authorize it.
*/
const ForbiddenError = message => new ApiError(403)
/**
* 404 NOT_FOUND
* The server understood the request but refuses to authorize it.
*/
const NotFoundError = message => ApiError(404)
/**
* 500 INTERNAL SERVER ERROR
* The server encountered an unexpected condition that prevented
* it from fulfilling the request.
*/
const InternalServerError = message => ApiError(500)
/**
* 503 SERVICE UNAVAILABLE
* The server is currently unable to handle the request due to a temporary problem
*/
const ServiceUnavailableError = message => ApiError(503)
module.exports = {
BadRequestError,
UnauthorizedError,
ForbiddenError,
NotFoundError,
InternalServerError,
ServiceUnavailableError
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment