Skip to main content
Memberstack Docs
Dashboard

Error Handling

Memberstack provides a rich error handling system with structured error objects, utility functions for extracting error information, and constants for the most common error codes. Errors returned by the Memberstack API carry a machine-readable code and message; a few failures reject with something else: a plain string such as "Unauthorized" (most commonly a members-only method called while logged out), or an object with only a message and no code (for example an invalid public key).

/dom-package/error-handling.md
Quick Overview

All error utilities are exported directly from @memberstack/dom. Import them alongside any other methods you use.

Error Object Structure

When a Memberstack method fails, it throws the error body the API returned. For coded errors that is an object with a machine-readable code and a human-readable message, plus category, suggestions and docsUrl. The HTTP status is not on the thrown object. Some logged-out calls reject with the plain string "Unauthorized" instead; isMemberstackError() returns false for those and getErrorMessage() returns the string. A third shape is an object with only a message and no code (an invalid public key, and most provider popup errors): isMemberstackError() is false for it too, and getErrorMessage() returns its generic default, so read error.message yourself: const text = typeof error === "string" ? error : (error?.message ?? getErrorMessage(error)).

// A coded API error (here: a wrong password)
{
  code: "invalid-credentials",                        // Machine-readable error code
  message: "The provided credentials are invalid.",   // The API's message (or your custom error text)
  category: "authentication",
  suggestions: ["Verify the email address is spelled correctly", "..."],
  docsUrl: "https://docs.memberstack.com/..."
}
// There is no statusCode: the SDK does not expose the HTTP status.

Most coded API errors carry category and suggestions, and usually docsUrl. Some do not (use-social-login, which carries providerKey instead; errors the SDK creates itself such as network-error; uncoded generic-message errors), so read them through the helpers (getErrorCategory(), getErrorSuggestions(), getErrorDocsUrl(), or all at once with getErrorReport()): each returns the value on the error when present and otherwise falls back to a built-in lookup keyed by error code.

The getErrorSuggestions() array is useful while debugging: each entry is a next step for the developer, and many name SDK methods or dashboard settings. Review them before showing any to end users.

Utility Functions

Memberstack exports helper functions for safely extracting information from error objects. These are safer than accessing properties directly because they handle cases where the error may not be a Memberstack error.

import {
  isErrorCode,
  getErrorMessage,
  getErrorCode,
  getErrorCategory,
  getErrorSuggestions,
  getErrorDocsUrl,
  formatErrorForUser,
  getErrorReport,
  isMemberstackError,
  ErrorCodes
} from '@memberstack/dom';

getErrorMessage(error)

Extracts the human-readable error message from any error object.

try {
  await memberstack.loginMemberEmailPassword({ email, password });
} catch (error) {
  const message = getErrorMessage(error);
  // "The provided credentials are invalid."
  // (the API's message, including any custom error text set in your dashboard;
  //  formatErrorForUser() returns the SDK's own wording instead)

  // Display to user
  document.getElementById('error').textContent = message;
}

isErrorCode(error, code)

Checks if an error matches a specific error code. Use this with the ErrorCodes constant for type-safe error checking.

import { isErrorCode, getErrorMessage, ErrorCodes } from '@memberstack/dom';

try {
  await memberstack.signupMemberEmailPassword({ email, password });
} catch (error) {
  if (isErrorCode(error, ErrorCodes.EMAIL_ALREADY_EXISTS)) {
    // Suggest logging in instead
    showMessage("This email is already registered. Try logging in.");
  } else if (isErrorCode(error, ErrorCodes.PASSWORD_TOO_SHORT)) {
    showMessage("Password must be at least 8 characters.");
  } else if (isErrorCode(error, ErrorCodes.INVALID_EMAIL)) {
    showMessage("Please enter a valid email address.");
  } else {
    showMessage(getErrorMessage(error));
  }
}

getErrorCategory(error)

Returns the error category, useful for grouping errors in your UI or logging.

const category = getErrorCategory(error);

switch (category) {
  case 'authentication':
    // Show login-related error UI
    break;
  case 'validation':
    // Highlight invalid form fields
    break;
  case 'payment':
    // Show payment-related error UI
    break;
  case 'authorization':
    // Show access denied message
    break;
  case 'not_found':
    // Show "not found" message
    break;
  case 'network':
    // Show "check your connection" message
    break;
}

// Available categories:
// 'authentication' | 'authorization' | 'validation' | 'not_found'
// 'conflict' | 'payment' | 'limit' | 'account'
// 'data_tables' | 'network' | 'unknown'

getErrorSuggestions(error)

Returns an array of actionable suggestions for resolving the error. They are written for developers (many reference SDK methods), so log them or show them in development rather than rendering them to members unfiltered.

const suggestions = getErrorSuggestions(error);
// ["Verify the email address is spelled correctly",
//  "Check if Caps Lock is enabled when entering the password",
//  "Use sendMemberResetPasswordEmail() if you forgot your password", ...]

if (suggestions?.length) {
  suggestions.forEach(suggestion => {
    const li = document.createElement('li');
    li.textContent = suggestion;
    errorList.appendChild(li);
  });
}

formatErrorForUser(error)

Returns a concise, user-friendly message for the error, a curated message keyed off the error code (it does not append the suggestions list). This is the quickest way to show a helpful error to your users. It ignores the API's own message, including custom error text set in your dashboard and the text of generic-message errors; use getErrorMessage() when you want the API's wording.

try {
  await memberstack.loginMemberEmailPassword({ email, password });
} catch (error) {
  const userMessage = formatErrorForUser(error);
  alert(userMessage);
  // Example output (a single curated sentence):
  // "Invalid email or password. Please check your credentials and try again."
}

isMemberstackError(error)

Type guard that checks whether a caught value is a Memberstack error object (API errors and the SDK's own network-error), as opposed to a TypeError from your own code or a plain-string rejection such as "Unauthorized".

try {
  await memberstack.signupMemberEmailPassword({ email, password });
} catch (error) {
  if (isMemberstackError(error)) {
    // .code and .message are present; read .category / .suggestions through
    // the helpers so SDK-created errors (network-error) work too
    console.log('Memberstack error:', error.code, error.message);
  } else {
    // Not a coded Memberstack error: a bug in your own code, a plain-string
    // rejection such as "Unauthorized", or an object with only a message
    console.error('Unexpected error:', error);
  }
}

getErrorReport(error)

Returns a detailed error report object with all available information. Useful for logging and debugging.

const report = getErrorReport(error);
// {
//   code: "invalid-credentials",
//   message: "The provided credentials are invalid.",
//   category: "authentication",
//   suggestions: ["Verify the email...", "Check if Caps Lock..."],
//   docsUrl: "https://docs.memberstack.com/..."
// }

// Log to your error tracking service
errorTracker.captureError(report);

Error Codes Reference

Use the ErrorCodes constant for type-safe error code checking. All codes are accessible as properties on the ErrorCodes object.

import { ErrorCodes, isErrorCode } from '@memberstack/dom';

// Use with isErrorCode() for type-safe checking
if (isErrorCode(error, ErrorCodes.INVALID_CREDENTIALS)) {
  // handle invalid credentials
}

Authentication Errors

ErrorCodes ConstantCode ValueDescription
INVALID_CREDENTIALSinvalid-credentialsWrong email or password
INVALID_TOKENclient/invalid-tokenReserved. An invalid or expired session currently surfaces as a logged-out member (getCurrentMember() returns null); members-only calls reject with the plain string "Unauthorized", or with login-required from addPlan, purchasePlansWithCheckout and launchStripeCustomerPortal
MEMBER_NOT_FOUNDmember-not-foundNot returned by the browser SDK. An unknown email on login returns invalid-credentials
INVALID_RESET_CODEinvalid-reset-codeInvalid or expired password reset code
INVALID_PASSWORDLESS_CODEinvalid-passwordless-login-codeInvalid or expired passwordless code
LOGIN_REQUIREDlogin-requiredMember must be logged in

Account & Social Login Errors

ErrorCodes ConstantCode ValueDescription
EMAIL_ALREADY_EXISTSemail-already-in-useEmail is already registered
USE_SOCIAL_LOGINuse-social-loginAccount registered via social provider
USE_EMAIL_LOGINuse-email-loginAccount registered with email/password
NO_PASSWORD_SETno-password-setMember doesn't have a password set
ACCOUNT_ALREADY_CONNECTEDaccount-already-connectedProvider already connected to this account
ACCOUNT_NOT_CONNECTEDaccount-not-connectedProvider not connected to this account
ACCOUNT_CONNECT_FAILEDaccount-connect-failedFailed to connect provider
ACCOUNT_CONNECT_REQUIRES_LOGINaccount-connect-requires-loginMust be logged in to connect a provider
ACCOUNT_SET_PASSWORD_FIRSTaccount-set-password-before-disconnectSet a password before disconnecting the only provider
ACCOUNT_NOT_FOUNDaccount-not-foundNo account found for this provider

Validation Errors

ErrorCodes ConstantCode ValueDescription
INVALID_EMAILinvalid-emailInvalid email format
INVALID_PASSWORDinvalid-passwordCurrent password is incorrect (updateMemberAuth). A too-short new password returns invalid-password-too-short
PASSWORD_TOO_SHORTinvalid-password-too-shortPassword is too short (min 8 characters)
REQUIRED_FIELD_MISSINGrequired-field-missingA required field was not provided
INVALID_CAPTCHAinvalid-captchaCaptcha verification failed

Plan & Subscription Errors

ErrorCodes ConstantCode ValueDescription
PLAN_NOT_FOUNDplan-not-foundPlan ID doesn't exist
NO_PLAN_FOUNDno-plan-foundNo plan found for this member
ALREADY_HAS_PLANalready-have-planMember already has this plan
PLAN_NOT_FREEplan-not-freeCannot add a paid plan with addPlan()
PLAN_MEMBER_LIMIT_REACHEDplan-member-limit-reachedPlan has reached its member limit
PLAN_RESTRICTED_TO_ADMINplan-restricted-to-adminPlan can only be assigned by admin
DOMAIN_NOT_PERMITTEDdomain-not-permittedEmail domain not allowed for this plan
PRICE_NOT_AVAILABLEprice-no-longer-availablePrice is no longer available

Team Errors

ErrorCodes ConstantCode ValueDescription
TEAM_FULLteam-fullTeam has reached its seat limit
ONE_ACTIVE_TEAM_ONLYcan-only-have-one-active-teamA member can only belong to one active team
CANNOT_CHANGE_TEAMcannot-change-team-accountRemove team members before making this change

Data Table Errors

ErrorCodes ConstantCode ValueDescription
DATA_TABLE_NOT_FOUNDdata-table-not-foundTable key doesn't exist
DATA_RECORD_NOT_FOUNDdata-record-not-foundRecord ID doesn't exist
INVALID_TABLE_KEYinvalid-table-keyInvalid table key format
UNIQUE_CONSTRAINT_VIOLATIONunique-constraint-violationDuplicate value in unique field
FIELD_LIMIT_EXCEEDEDfield-limit-exceededToo many fields in table
INVALID_FIELD_TYPEinvalid-field-typeWrong data type for field
INVALID_FIELD_VALUEinvalid-field-valueInvalid value for field

Other Errors

ErrorCodes ConstantCode ValueDescription
ACCESS_DENIEDaccess-deniedInsufficient permissions
INVALID_FILE_TYPEinvalid-file-typeUnsupported file type for upload
FILE_TOO_LARGEfile-size-too-largeFile exceeds size limit
APP_NOT_FOUNDapp-not-foundApplication not found for this key
TEST_MODE_LIMIT_REACHEDtest-mode-member-limit-reachedSandbox member limit reached
NETWORK_ERRORnetwork-errorNetwork connection issue
UNKNOWN_ERRORunknown-errorReserved; not currently thrown

The API can also return codes that have no ErrorCodes constant, most often generic-message (an uncoded error: read its message), plus a few specific ones such as wrong-environment-key and passwordless-email-not-found. Compare against the string directly, e.g. getErrorCode(error) === "generic-message".

Complete Example

Here's a full example showing how to use the error handling utilities together in a signup form.

import memberstackDOM, {
  isErrorCode,
  ErrorCodes,
  formatErrorForUser,
  isMemberstackError
} from '@memberstack/dom';

// The default export only has init(); call methods on the instance it returns.
const memberstack = memberstackDOM.init({ publicKey: 'YOUR_PUBLIC_KEY' });

async function handleSignup(email, password) {
  try {
    const result = await memberstack.signupMemberEmailPassword({
      email,
      password
    });
    // Success - redirect or update UI
    window.location.href = result.data.redirect || '/dashboard';
  } catch (error) {
    // Check for specific error codes
    if (isErrorCode(error, ErrorCodes.EMAIL_ALREADY_EXISTS)) {
      showError('This email is already registered. Would you like to log in instead?');
      showLoginLink();
      return;
    }

    if (isErrorCode(error, ErrorCodes.PASSWORD_TOO_SHORT)) {
      showError('Password must be at least 8 characters.');
      highlightField('password');
      return;
    }

    if (isErrorCode(error, ErrorCodes.INVALID_EMAIL)) {
      showError('Please enter a valid email address.');
      highlightField('email');
      return;
    }

    if (isErrorCode(error, ErrorCodes.TEST_MODE_LIMIT_REACHED)) {
      showError('Test mode member limit reached. Delete some test members or switch to live mode.');
      return;
    }

    // For any other Memberstack error (including network-error), show the
    // SDK's curated one-line message
    if (isMemberstackError(error)) {
      showError(formatErrorForUser(error));
    } else {
      // Not a coded Memberstack error: a plain string such as "Unauthorized",
      // an object with only a message (e.g. an invalid public key), or a bug
      // in this handler. Log it so the real message is not lost.
      showError('Something went wrong. Please try again.');
      console.error('Unexpected error:', error);
    }
  }
}

Framework Examples

React

import { useState } from 'react';
import { isErrorCode, ErrorCodes, getErrorMessage, getErrorSuggestions } from '@memberstack/dom';

function LoginForm({ memberstack }) {
  const [error, setError] = useState(null);
  const [suggestions, setSuggestions] = useState([]);

  async function handleLogin(e) {
    e.preventDefault();
    setError(null);
    setSuggestions([]);

    const formData = new FormData(e.target);

    try {
      await memberstack.loginMemberEmailPassword({
        email: formData.get('email'),
        password: formData.get('password')
      });
    } catch (err) {
      setError(getErrorMessage(err));
      setSuggestions(getErrorSuggestions(err) || []);
    }
  }

  return (
    <form onSubmit={handleLogin}>
      <input name="email" type="email" placeholder="Email" />
      <input name="password" type="password" placeholder="Password" />
      <button type="submit">Log In</button>

      {error && (
        <div className="error">
          <p>{error}</p>
          {suggestions.length > 0 && (
            <ul>
              {suggestions.map((s, i) => <li key={i}>{s}</li>)}
            </ul>
          )}
        </div>
      )}
    </form>
  );
}

Svelte 5

<script>
  import { getErrorMessage, getErrorSuggestions, isErrorCode, ErrorCodes } from '@memberstack/dom';
  import { getMemberstack } from '$lib/memberstack';

  let error = $state(null);
  let suggestions = $state([]);

  async function handleLogin(email, password) {
    error = null;
    suggestions = [];
    const ms = getMemberstack();

    try {
      await ms.loginMemberEmailPassword({ email, password });
    } catch (err) {
      error = getErrorMessage(err);
      suggestions = getErrorSuggestions(err) || [];
    }
  }
</script>

{#if error}
  <div class="error">
    <p>{error}</p>
    {#if suggestions.length > 0}
      <ul>
        {#each suggestions as suggestion}
          <li>{suggestion}</li>
        {/each}
      </ul>
    {/if}
  </div>
{/if}
Need help?
Can't find what you're looking for? Our team is here to help.