On this simple trick, I'll show you how to create a Factory method pattern.
function HttpErrorFactory(statusCode, error = 'Uncaught Error!') {
if (!statusCode) {
throw new Error('Invalid status code.');
}
function make() {
return {
statusCode,
error,
};
}
function print() {
const _response = make();
return console.log(JSON.stringify(_response));
}
return {
make,
print
};
}
const badRequest = HttpErrorFactory(400, 'Bad Request!');
const badRequestObject = badRequest.make();
const internalServerError = HttpErrorFactory(500, 'Internal Server Error!');
const internalServerErrorObject = internalServerError.make();
console.log(badRequestObject);
/**
* => {
error: "Bad Request!",
statusCode: 400
}
*/
console.log(internalServerErrorObject);
/**
* => {
error: "Internal Server Error!",
statusCode: 500
}
*/
internalServerError.print();
// => "{\"statusCode\":500,\"error\":\"Internal Server Error!\"}"
badRequest.print();
// => "{\"statusCode\":400,\"error\":\"Bad Request!\"}"
Did you like it? Comment, share! ✨
Top comments (0)