vendredi 26 novembre 2021

JS Good Practices - Creating related exceptions with factories?

Is it a "good practice" to create errors related with a same concept via factory?

I mean, for example, in a sign up validation, could it be a good practice to do the following?

"use strict";

const { functions } = require("../../../services/firebase")

const authErrors = Object.freeze({
  invalidPassword() {
    return new functions.https.HttpsError(
      "invalid-argument",
      "Invalid password.",
      {
        status: "error",
        code: "auth/invalid-password",
        message: "The provided password is invalid. It must contain between 8 and 40 characters, including at least one uppercase letter, one lowercase letter, and a number.",
      }
    );
  },
  invalidUsername() {
    return new functions.https.HttpsError(
      "invalid-argument",
      "Invalid username.",
      {
        status: "error",
        code: "auth/invalid-username",
        message: "Username must be between 3 and 30 characters, including numbers, letters, hyphens, periods, or underscores.",
      }
    );
  },
  // ... more related errors 
});

module.exports = authErrors;

and then use them as follows?

if (!validateUsername(username)) {
  throw authErrors.invalidUsername();
}

Note: I am using Google Cloud Functions, and it has no sense for my use case to throw instances of custom errors.

Aucun commentaire:

Enregistrer un commentaire