Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions src/adapty-error.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ErrorCode } from '@/types/error';
import { ErrorCode, ErrorCodeName, getErrorCodeName } from '@/types/error';

export interface AdaptyErrorInput {
adaptyCode: ErrorCode;
Expand Down Expand Up @@ -29,6 +29,11 @@ export class AdaptyError extends Error {
}
}

/** Name of {@link adaptyCode}, or `undefined` if the code is newer than this SDK version. */
public get codeName(): ErrorCodeName | undefined {
return getErrorCodeName(this.adaptyCode);
}

public static set onError(callback: (error: AdaptyError) => void) {
AdaptyError.middleware = callback;
}
Expand Down Expand Up @@ -60,7 +65,7 @@ export class AdaptyError extends Error {

private static getMessage(input: AdaptyErrorInput): string {
const code = input.adaptyCode;
const codeText = ErrorCode[code];
const codeText = getErrorCodeName(code) ?? 'unknown code';

let message = `#${code} (${codeText}): ${input.message}`;

Expand Down
2 changes: 1 addition & 1 deletion src/coders/adapty-native-error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export class AdaptyNativeErrorCoder

public getError(data: Model): AdaptyError {
return new AdaptyError({
adaptyCode: data.adaptyCode as AdaptyError['adaptyCode'],
adaptyCode: data.adaptyCode,
message: data.message,
detail: data.detail,
});
Expand Down
57 changes: 57 additions & 0 deletions src/types/error.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { AdaptyError } from '@/adapty-error';
import {
ErrorCode,
ErrorCodeName,
getErrorCode,
getErrorCodeName,
getErrorPrompt,
isKnownErrorCode,
} from './error';

describe('error codes', () => {
it('keeps ErrorCode and ErrorCodeName in sync', () => {
const fromMapping = Object.entries(ErrorCode).map(
([code, name]) => [name, Number(code)] as const,
);

expect(Object.fromEntries(fromMapping)).toStrictEqual(ErrorCodeName);
});

it.each([
[2, 'paymentCancelled'],
[1020, 'fetchSubscriptionStatusFailed'],
[1030, 'unknownTransactionId'],
[1050, 'paymentPendingError'],
[1060, 'billingPlanUnavailable'],
[3020, 'unidentifiedUserLogout'],
[4104, 'wrongAssetType'],
[4105, 'jsException'],
[4106, 'navigatorNotFound'],
[4107, 'invalidActionUrl'],
] as const)('maps native code %i to %s', (code, name) => {
expect(getErrorPrompt(code)).toBe(name);
expect(getErrorCode(name)).toBe(code);
});

it('accepts a code unknown to this SDK version', () => {
const error = new AdaptyError({ adaptyCode: 7777, message: 'New error' });

expect(isKnownErrorCode(7777)).toBe(false);
expect(getErrorCodeName(7777)).toBeUndefined();
expect(getErrorPrompt(7777)).toBe('Unknown code: 7777');
expect(error.adaptyCode === 7777).toBe(true);
expect(error.codeName).toBeUndefined();
expect(error.message).toBe('#7777 (unknown code): New error');
});

it('names a known code', () => {
const error = new AdaptyError({ adaptyCode: 1060, message: 'Unavailable' });

expect(isKnownErrorCode(1060)).toBe(true);
expect(error.adaptyCode === ErrorCodeName.billingPlanUnavailable).toBe(
true,
);
expect(error.codeName).toBe('billingPlanUnavailable');
expect(error.message).toBe('#1060 (billingPlanUnavailable): Unavailable');
});
});
76 changes: 62 additions & 14 deletions src/types/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ const ErrorCodeMapping = Object.freeze({
* Client is not allowed to make a request, etc.
*/
1: 'clientInvalid',
/**
* The user cancelled the payment request.
*/
2: 'paymentCancelled',
/**
* Invalid purchase identifier, etc.
*/
Expand Down Expand Up @@ -95,6 +99,17 @@ const ErrorCodeMapping = Object.freeze({
1006: 'productPurchaseFailed',
1010: 'refreshReceiptFailed',
1011: 'receiveRestoredTransactionsFailed',
1020: 'fetchSubscriptionStatusFailed',
1030: 'unknownTransactionId',
/**
* The payment is deferred, e.g. awaiting Ask to Buy approval.
*/
1050: 'paymentPendingError',
/**
* The product doesn't offer the requested billing plan on this device
* (e.g. a 12-month commitment plan below iOS 26.4). iOS only.
*/
1060: 'billingPlanUnavailable',

/**
* You need to be authenticated to perform requests.
Expand All @@ -120,6 +135,10 @@ const ErrorCodeMapping = Object.freeze({
*/
3006: 'profileWasChanged',
3007: 'unsupportedData',
/**
* `logout` was called for a user that was never identified.
*/
3020: 'unidentifiedUserLogout',
3100: 'persistingDataError',
3101: 'fetchTimeoutError',
/**
Expand All @@ -132,15 +151,32 @@ const ErrorCodeMapping = Object.freeze({
* (e.g. no foreground-active window scene to show store messages).
*/
3202: 'resolverFailure',
/**
* Custom Android AdaptyUI codes.
*/
4104: 'wrongAssetType',
4105: 'jsException',
4106: 'navigatorNotFound',
4107: 'invalidActionUrl',
9000: 'operationInterrupted',
});

export const ErrorCode = ErrorCodeMapping;
export type ErrorCode = keyof typeof ErrorCodeMapping;
/** A code known to this version of the SDK. */
export type KnownErrorCode = keyof typeof ErrorCodeMapping;
/**
* Code of an {@link AdaptyError}.
*
* @remarks
* Native SDKs may send codes this version doesn't know yet, so any number is accepted.
* Known codes still autocomplete; use {@link isKnownErrorCode} to narrow.
*/
export type ErrorCode = KnownErrorCode | (number & {});

export const ErrorCodeName = Object.freeze({
unknown: 0,
clientInvalid: 1,
paymentCancelled: 2,
paymentInvalid: 3,
paymentNotAllowed: 4,
storeProductNotAvailable: 5,
Expand Down Expand Up @@ -174,6 +210,10 @@ export const ErrorCodeName = Object.freeze({
productPurchaseFailed: 1006,
refreshReceiptFailed: 1010,
receiveRestoredTransactionsFailed: 1011,
fetchSubscriptionStatusFailed: 1020,
unknownTransactionId: 1030,
paymentPendingError: 1050,
billingPlanUnavailable: 1060,
notActivated: 2002,
badRequest: 2003,
serverError: 2004,
Expand All @@ -185,35 +225,43 @@ export const ErrorCodeName = Object.freeze({
activateOnceError: 3005,
profileWasChanged: 3006,
unsupportedData: 3007,
unidentifiedUserLogout: 3020,
persistingDataError: 3100,
fetchTimeoutError: 3101,
operationInProgress: 3201,
resolverFailure: 3202,
wrongAssetType: 4104,
jsException: 4105,
navigatorNotFound: 4106,
invalidActionUrl: 4107,
operationInterrupted: 9000,
} as const);
export type ErrorCodeName = keyof typeof ErrorCodeName;

export function getErrorCode(
error: (typeof ErrorCode)[ErrorCode],
): ErrorCode | undefined {
export function isKnownErrorCode(code: number): code is KnownErrorCode {
return Object.prototype.hasOwnProperty.call(ErrorCodeMapping, code);
}

/** Returns the name of a code, or `undefined` for a code unknown to this SDK version. */
export function getErrorCodeName(code: number): ErrorCodeName | undefined {
return isKnownErrorCode(code) ? ErrorCodeMapping[code] : undefined;
}

export function getErrorCode(error: ErrorCodeName): KnownErrorCode | undefined {
const errorCode = Object.keys(ErrorCode).find(keyStr => {
const key = Number(keyStr) as ErrorCode;
const key = Number(keyStr) as KnownErrorCode;
return ErrorCode[key] === error;
});

if (!errorCode) {
return undefined;
}

return Number(errorCode) as ErrorCode;
return Number(errorCode) as KnownErrorCode;
}

export function getErrorPrompt(code: ErrorCode): (typeof ErrorCode)[ErrorCode] {
const prompt = ErrorCode[code];

if (!prompt) {
return `Unknown code: ${code}` as (typeof ErrorCode)[ErrorCode];
}

return prompt;
export function getErrorPrompt(
code: ErrorCode,
): ErrorCodeName | `Unknown code: ${number}` {
return getErrorCodeName(code) ?? `Unknown code: ${code}`;
}
Loading