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).
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 Constant | Code Value | Description |
|---|---|---|
INVALID_CREDENTIALS | invalid-credentials | Wrong email or password |
INVALID_TOKEN | client/invalid-token | Reserved. 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_FOUND | member-not-found | Not returned by the browser SDK. An unknown email on login returns invalid-credentials |
INVALID_RESET_CODE | invalid-reset-code | Invalid or expired password reset code |
INVALID_PASSWORDLESS_CODE | invalid-passwordless-login-code | Invalid or expired passwordless code |
LOGIN_REQUIRED | login-required | Member must be logged in |
Account & Social Login Errors
| ErrorCodes Constant | Code Value | Description |
|---|---|---|
EMAIL_ALREADY_EXISTS | email-already-in-use | Email is already registered |
USE_SOCIAL_LOGIN | use-social-login | Account registered via social provider |
USE_EMAIL_LOGIN | use-email-login | Account registered with email/password |
NO_PASSWORD_SET | no-password-set | Member doesn't have a password set |
ACCOUNT_ALREADY_CONNECTED | account-already-connected | Provider already connected to this account |
ACCOUNT_NOT_CONNECTED | account-not-connected | Provider not connected to this account |
ACCOUNT_CONNECT_FAILED | account-connect-failed | Failed to connect provider |
ACCOUNT_CONNECT_REQUIRES_LOGIN | account-connect-requires-login | Must be logged in to connect a provider |
ACCOUNT_SET_PASSWORD_FIRST | account-set-password-before-disconnect | Set a password before disconnecting the only provider |
ACCOUNT_NOT_FOUND | account-not-found | No account found for this provider |
Validation Errors
| ErrorCodes Constant | Code Value | Description |
|---|---|---|
INVALID_EMAIL | invalid-email | Invalid email format |
INVALID_PASSWORD | invalid-password | Current password is incorrect (updateMemberAuth). A too-short new password returns invalid-password-too-short |
PASSWORD_TOO_SHORT | invalid-password-too-short | Password is too short (min 8 characters) |
REQUIRED_FIELD_MISSING | required-field-missing | A required field was not provided |
INVALID_CAPTCHA | invalid-captcha | Captcha verification failed |
Plan & Subscription Errors
| ErrorCodes Constant | Code Value | Description |
|---|---|---|
PLAN_NOT_FOUND | plan-not-found | Plan ID doesn't exist |
NO_PLAN_FOUND | no-plan-found | No plan found for this member |
ALREADY_HAS_PLAN | already-have-plan | Member already has this plan |
PLAN_NOT_FREE | plan-not-free | Cannot add a paid plan with addPlan() |
PLAN_MEMBER_LIMIT_REACHED | plan-member-limit-reached | Plan has reached its member limit |
PLAN_RESTRICTED_TO_ADMIN | plan-restricted-to-admin | Plan can only be assigned by admin |
DOMAIN_NOT_PERMITTED | domain-not-permitted | Email domain not allowed for this plan |
PRICE_NOT_AVAILABLE | price-no-longer-available | Price is no longer available |
Team Errors
| ErrorCodes Constant | Code Value | Description |
|---|---|---|
TEAM_FULL | team-full | Team has reached its seat limit |
ONE_ACTIVE_TEAM_ONLY | can-only-have-one-active-team | A member can only belong to one active team |
CANNOT_CHANGE_TEAM | cannot-change-team-account | Remove team members before making this change |
Data Table Errors
| ErrorCodes Constant | Code Value | Description |
|---|---|---|
DATA_TABLE_NOT_FOUND | data-table-not-found | Table key doesn't exist |
DATA_RECORD_NOT_FOUND | data-record-not-found | Record ID doesn't exist |
INVALID_TABLE_KEY | invalid-table-key | Invalid table key format |
UNIQUE_CONSTRAINT_VIOLATION | unique-constraint-violation | Duplicate value in unique field |
FIELD_LIMIT_EXCEEDED | field-limit-exceeded | Too many fields in table |
INVALID_FIELD_TYPE | invalid-field-type | Wrong data type for field |
INVALID_FIELD_VALUE | invalid-field-value | Invalid value for field |
Other Errors
| ErrorCodes Constant | Code Value | Description |
|---|---|---|
ACCESS_DENIED | access-denied | Insufficient permissions |
INVALID_FILE_TYPE | invalid-file-type | Unsupported file type for upload |
FILE_TOO_LARGE | file-size-too-large | File exceeds size limit |
APP_NOT_FOUND | app-not-found | Application not found for this key |
TEST_MODE_LIMIT_REACHED | test-mode-member-limit-reached | Sandbox member limit reached |
NETWORK_ERROR | network-error | Network connection issue |
UNKNOWN_ERROR | unknown-error | Reserved; 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}