DEV Community

Helder Burato Berto
Helder Burato Berto

Posted on

6 3

🔥 Quick Tip: How to create a Factory method pattern

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!\"}"
Enter fullscreen mode Exit fullscreen mode

Did you like it? Comment, share! ✨

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more