Skip to content

A local-first personal finance app

[AI] Surface the real GoCardless error reason in the UI (#8778)

Zannis Kalampoukis6e68ee1de1c5
diff --git a/packages/desktop-client/package.json b/packages/desktop-client/package.json
index 6cb003b41c..182c18327b 100644
--- a/packages/desktop-client/package.json
+++ b/packages/desktop-client/package.json
@@ -35,6 +35,7 @@
"#mocks/*": "./src/mocks/*.ts",
"#components/forms": "./src/components/forms/index.tsx",
"#components/banksync": "./src/components/banksync/index.tsx",
+ "#components/banksync/bankSyncErrors": "./src/components/banksync/bankSyncErrors.ts",
"#components/banksync/bankSyncUtils": "./src/components/banksync/bankSyncUtils.ts",
"#components/banksync/BuiltInProviders": "./src/components/banksync/BuiltInProviders.tsx",
"#components/banksync/useBuiltInBankSyncProviders": "./src/components/banksync/useBuiltInBankSyncProviders.ts",
diff --git a/packages/desktop-client/src/components/banksync/bankSyncErrors.test.ts b/packages/desktop-client/src/components/banksync/bankSyncErrors.test.ts
new file mode 100644
index 0000000000..7e6991d45f
--- /dev/null
+++ b/packages/desktop-client/src/components/banksync/bankSyncErrors.test.ts
@@ -0,0 +1,87 @@
+import { describe, expect, it } from 'vitest';
+
+import { getBankSyncErrorReason } from './bankSyncErrors';
+
+describe('getBankSyncErrorReason', () => {
+ it('combines the classification with the reason GoCardless gave', () => {
+ expect(
+ getBankSyncErrorReason({
+ error_code: 'INTERNAL_ERROR',
+ error_type: 'IP address access denied',
+ error_details: {
+ status: 403,
+ summary: 'IP address access denied',
+ detail:
+ "Your IP 203.0.113.7 isn't whitelisted to perform this action",
+ },
+ }),
+ ).toBe(
+ "IP address access denied: Your IP 203.0.113.7 isn't whitelisted to perform this action",
+ );
+ });
+
+ it('does not repeat the summary when it duplicates the detail', () => {
+ expect(
+ getBankSyncErrorReason({
+ error_type: 'Rate limit exceeded',
+ error_details: {
+ status: 429,
+ summary: 'Rate limit exceeded',
+ detail: 'Rate limit exceeded',
+ },
+ }),
+ ).toBe('Rate limit exceeded');
+ });
+
+ it('falls back to the summary when GoCardless sent no detail', () => {
+ expect(
+ getBankSyncErrorReason({
+ error_type: 'Invalid provided parameters',
+ error_details: { status: 400, summary: 'Invalid country choice.' },
+ }),
+ ).toBe('Invalid country choice.');
+ });
+
+ it('falls back to our own classification when GoCardless sent no body', () => {
+ expect(
+ getBankSyncErrorReason({
+ error_type:
+ 'Daily request limit set by the Institution has been exceeded',
+ error_details: { status: 429 },
+ }),
+ ).toBe('Daily request limit set by the Institution has been exceeded');
+ });
+
+ it('uses error_type alone when there are no GoCardless details at all', () => {
+ expect(getBankSyncErrorReason({ error_type: 'socket hang up' })).toBe(
+ 'socket hang up',
+ );
+ });
+
+ it('returns undefined when there is nothing meaningful to show', () => {
+ expect(getBankSyncErrorReason(undefined)).toBeUndefined();
+ expect(getBankSyncErrorReason(null)).toBeUndefined();
+ expect(getBankSyncErrorReason([])).toBeUndefined();
+ expect(getBankSyncErrorReason({})).toBeUndefined();
+ expect(getBankSyncErrorReason({ error_type: ' ' })).toBeUndefined();
+ expect(getBankSyncErrorReason('boom')).toBeUndefined();
+ });
+
+ it('ignores the placeholder internal-error string', () => {
+ expect(
+ getBankSyncErrorReason({
+ error_code: 'INTERNAL_ERROR',
+ error_type: 'internal-error',
+ }),
+ ).toBeUndefined();
+ });
+
+ it('ignores non-string values on the payload', () => {
+ expect(
+ getBankSyncErrorReason({
+ error_type: 42,
+ error_details: { summary: { nested: true }, detail: ['a'] },
+ }),
+ ).toBeUndefined();
+ });
+});
diff --git a/packages/desktop-client/src/components/banksync/bankSyncErrors.ts b/packages/desktop-client/src/components/banksync/bankSyncErrors.ts
new file mode 100644
index 0000000000..a767313364
--- /dev/null
+++ b/packages/desktop-client/src/components/banksync/bankSyncErrors.ts
@@ -0,0 +1,52 @@
+/**
+ * The sync server answers a failed bank-sync call with a `status: 'ok'`
+ * envelope whose payload describes the failure, so the error never throws on
+ * the client. These helpers turn that payload into something worth showing the
+ * user instead of a hard-coded guess at the cause.
+ */
+
+/** Placeholder the server sends when the error carried no message at all. */
+const INTERNAL_ERROR_PLACEHOLDER = 'internal-error';
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+function readText(value: unknown): string | undefined {
+ if (typeof value !== 'string') {
+ return undefined;
+ }
+
+ const trimmed = value.trim();
+ return trimmed ? trimmed : undefined;
+}
+
+/**
+ * Builds the human-readable reason a bank-sync call failed.
+ *
+ * Prefers the provider's own wording (`summary` / `detail`) over our generic
+ * classification, because the provider knows why it said no — an IP block and
+ * a rate limit both surface as "credentials might be misconfigured" otherwise.
+ * Returns `undefined` when the payload carries nothing worth showing, so the
+ * caller can fall back to its generic message.
+ */
+export function getBankSyncErrorReason(payload: unknown): string | undefined {
+ if (!isRecord(payload)) {
+ return undefined;
+ }
+
+ const classification = readText(payload.error_type);
+ const details = isRecord(payload.error_details)
+ ? payload.error_details
+ : undefined;
+
+ const summary = readText(details?.summary);
+ const detail = readText(details?.detail);
+
+ const headline = summary ?? classification;
+ if (headline === undefined || headline === INTERNAL_ERROR_PLACEHOLDER) {
+ return detail;
+ }
+
+ return detail && detail !== headline ? `${headline}: ${detail}` : headline;
+}
diff --git a/packages/desktop-client/src/components/modals/GoCardlessExternalMsgModal.test.tsx b/packages/desktop-client/src/components/modals/GoCardlessExternalMsgModal.test.tsx
index 6f2f95dd51..7cd7dfe393 100644
--- a/packages/desktop-client/src/components/modals/GoCardlessExternalMsgModal.test.tsx
+++ b/packages/desktop-client/src/components/modals/GoCardlessExternalMsgModal.test.tsx
@@ -1,10 +1,17 @@
-import { render, screen } from '@testing-library/react';
+import { sendCatch } from '@actual-app/core/platform/client/connection';
+import { act, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
import { vi } from 'vitest';
import { TestProviders } from '#mocks';
import { GoCardlessExternalMsgModal } from './GoCardlessExternalMsgModal';
+vi.mock('@actual-app/core/platform/client/connection', () => ({
+ send: vi.fn(),
+ sendCatch: vi.fn(),
+}));
+
vi.mock('#hooks/useGlobalPref', () => ({
useGlobalPref: () => [null],
}));
@@ -26,6 +33,10 @@ describe('GoCardlessExternalMsgModal - Country Auto-selection', () => {
const originalIntl = global.Intl;
const originalNavigator = global.navigator;
+ beforeEach(() => {
+ vi.mocked(sendCatch).mockResolvedValue({ data: [], error: undefined });
+ });
+
afterEach(() => {
global.Intl = originalIntl;
Object.defineProperty(global, 'navigator', {
@@ -136,3 +147,165 @@ describe('GoCardlessExternalMsgModal - Country Auto-selection', () => {
expect(countryInput).toHaveValue('France');
});
});
+
+describe('GoCardlessExternalMsgModal - Bank list errors', () => {
+ const mockProps = {
+ onMoveExternal: vi.fn(),
+ onSuccess: vi.fn(),
+ onClose: vi.fn(),
+ };
+
+ const originalIntl = global.Intl;
+ const originalNavigator = global.navigator;
+
+ beforeEach(() => {
+ // Pre-select a country so the modal actually fetches the bank list.
+ global.Intl = {
+ ...originalIntl,
+ DateTimeFormat: vi.fn(function () {
+ return { resolvedOptions: () => ({ timeZone: 'Europe/Berlin' }) };
+ }) as unknown as typeof Intl.DateTimeFormat,
+ } as typeof Intl;
+
+ Object.defineProperty(global, 'navigator', {
+ value: { language: 'en' },
+ writable: true,
+ });
+ });
+
+ afterEach(() => {
+ global.Intl = originalIntl;
+ Object.defineProperty(global, 'navigator', {
+ value: originalNavigator,
+ writable: true,
+ });
+ vi.clearAllMocks();
+ });
+
+ function renderModal() {
+ render(
+ <TestProviders>
+ <GoCardlessExternalMsgModal {...mockProps} />
+ </TestProviders>,
+ );
+ }
+
+ it('shows the reason GoCardless rejected the request', async () => {
+ vi.mocked(sendCatch).mockResolvedValue({
+ data: {
+ error_code: 'INTERNAL_ERROR',
+ error_type: 'IP address access denied',
+ error_details: {
+ status: 403,
+ summary: 'IP address access denied',
+ detail:
+ "Your IP 203.0.113.7 isn't whitelisted to perform this action",
+ },
+ },
+ error: undefined,
+ });
+
+ renderModal();
+
+ expect(
+ await screen.findByText(
+ /IP address access denied: Your IP 203\.0\.113\.7 isn't whitelisted to perform this action/,
+ ),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByText(/access credentials might be misconfigured/),
+ ).not.toBeInTheDocument();
+ });
+
+ it('shows the rate limit GoCardless reported', async () => {
+ vi.mocked(sendCatch).mockResolvedValue({
+ data: {
+ error_code: 'INTERNAL_ERROR',
+ error_type:
+ 'Daily request limit set by the Institution has been exceeded',
+ error_details: {
+ status: 429,
+ summary: 'Rate limit exceeded',
+ detail: 'The rate limit for this resource is 4/day',
+ },
+ },
+ error: undefined,
+ });
+
+ renderModal();
+
+ expect(
+ await screen.findByText(
+ /Rate limit exceeded: The rate limit for this resource is 4\/day/,
+ ),
+ ).toBeInTheDocument();
+ });
+
+ it('falls back to the generic message when the failure carries no reason', async () => {
+ vi.mocked(sendCatch).mockResolvedValue({
+ data: undefined,
+ error: { type: 'ServerError', code: 'network-failure' },
+ });
+
+ renderModal();
+
+ expect(
+ await screen.findByText(/access credentials might be misconfigured/),
+ ).toBeInTheDocument();
+ });
+
+ it('ignores the response of a request the user has already superseded', async () => {
+ type BankListResponse = Awaited<ReturnType<typeof sendCatch>>;
+
+ const resolvers: Array<(response: BankListResponse) => void> = [];
+ vi.mocked(sendCatch).mockImplementation(
+ () =>
+ new Promise<BankListResponse>(resolve => {
+ resolvers.push(resolve);
+ }),
+ );
+
+ renderModal();
+
+ // Germany is pre-selected, so its bank list is already in flight. Switch to
+ // France while that first request is still pending.
+ const countryInput = screen.getByPlaceholderText('(please select)');
+ await userEvent.clear(countryInput);
+ await userEvent.type(countryInput, 'France{Enter}');
+
+ await waitFor(() => expect(resolvers).toHaveLength(2));
+
+ // The newest request (France) lands first...
+ await act(async () => {
+ resolvers[1]({
+ data: [{ id: 'BANK_FR', name: 'French bank' }],
+ error: undefined,
+ });
+ });
+
+ // ...and the superseded German request fails afterwards.
+ await act(async () => {
+ resolvers[0]({
+ data: {
+ error_code: 'INTERNAL_ERROR',
+ error_type: 'IP address access denied',
+ error_details: {
+ status: 403,
+ summary: 'IP address access denied',
+ detail:
+ "Your IP 203.0.113.7 isn't whitelisted to perform this action",
+ },
+ },
+ error: undefined,
+ });
+ });
+
+ expect(
+ screen.queryByText(/IP address access denied/),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByText(/Failed loading available banks/),
+ ).not.toBeInTheDocument();
+ expect(screen.getByText('Choose your bank:')).toBeInTheDocument();
+ });
+});
diff --git a/packages/desktop-client/src/components/modals/GoCardlessExternalMsgModal.tsx b/packages/desktop-client/src/components/modals/GoCardlessExternalMsgModal.tsx
index e28eac6535..0e807b8b3f 100644
--- a/packages/desktop-client/src/components/modals/GoCardlessExternalMsgModal.tsx
+++ b/packages/desktop-client/src/components/modals/GoCardlessExternalMsgModal.tsx
@@ -15,6 +15,7 @@ import type {
import { Error, Warning } from '#components/alerts';
import { Autocomplete } from '#components/autocomplete/Autocomplete';
+import { getBankSyncErrorReason } from '#components/banksync/bankSyncErrors';
import { Link } from '#components/common/Link';
import { Modal, ModalCloseButton, ModalHeader } from '#components/common/Modal';
import { FormField, FormLabel } from '#components/forms';
@@ -30,10 +31,16 @@ function useAvailableBanks(country: string) {
const [banks, setBanks] = useState<GoCardlessInstitution[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [isError, setIsError] = useState(false);
+ const [errorReason, setErrorReason] = useState<string | null>(null);
useEffect(() => {
+ // Requests for a country the user has already moved on from must not
+ // overwrite the state of the request that replaced them.
+ let isCurrentRequest = true;
+
async function fetch() {
setIsError(false);
+ setErrorReason(null);
if (!country) {
setBanks([]);
@@ -45,8 +52,13 @@ function useAvailableBanks(country: string) {
const { data, error } = await sendCatch('gocardless-get-banks', country);
+ if (!isCurrentRequest) {
+ return;
+ }
+
if (error || !Array.isArray(data)) {
setIsError(true);
+ setErrorReason(getBankSyncErrorReason(data) ?? null);
setBanks([]);
} else {
setBanks(data);
@@ -56,12 +68,17 @@ function useAvailableBanks(country: string) {
}
void fetch();
+
+ return () => {
+ isCurrentRequest = false;
+ };
}, [setBanks, setIsLoading, country]);
return {
data: banks,
isLoading,
isError,
+ errorReason,
};
}
@@ -122,6 +139,7 @@ export function GoCardlessExternalMsgModal({
data: bankOptions,
isLoading: isBankOptionsLoading,
isError: isBankOptionError,
+ errorReason: bankOptionErrorReason,
} = useAvailableBanks(country);
const {
configuredGoCardless: isConfigured,
@@ -189,18 +207,34 @@ export function GoCardlessExternalMsgModal({
{isBankOptionError ? (
<Error>
- <Trans>
- Failed loading available banks: GoCardless access credentials
- might be misconfigured. Please{' '}
- <Link
- variant="text"
- onClick={onGoCardlessInit}
- style={{ color: theme.formLabelText, display: 'inline' }}
- >
- set them up
- </Link>{' '}
- again.
- </Trans>
+ {bankOptionErrorReason ? (
+ <Trans>
+ Failed loading available banks:{' '}
+ {{ reason: bankOptionErrorReason }}. If this is a credentials
+ problem, you can{' '}
+ <Link
+ variant="text"
+ onClick={onGoCardlessInit}
+ style={{ color: theme.formLabelText, display: 'inline' }}
+ >
+ set them up
+ </Link>{' '}
+ again.
+ </Trans>
+ ) : (
+ <Trans>
+ Failed loading available banks: GoCardless access credentials
+ might be misconfigured. Please{' '}
+ <Link
+ variant="text"
+ onClick={onGoCardlessInit}
+ style={{ color: theme.formLabelText, display: 'inline' }}
+ >
+ set them up
+ </Link>{' '}
+ again.
+ </Trans>
+ )}
</Error>
) : (
country &&
diff --git a/packages/sync-server/src/app-gocardless/app-gocardless.test.ts b/packages/sync-server/src/app-gocardless/app-gocardless.test.ts
index 61a183244a..c3f8852aa0 100644
--- a/packages/sync-server/src/app-gocardless/app-gocardless.test.ts
+++ b/packages/sync-server/src/app-gocardless/app-gocardless.test.ts
@@ -3,6 +3,7 @@ import request from 'supertest';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { GoCardlessRequisitionId } from './gocardless-node.types';
+import { mockInstitution } from './services/tests/fixtures';
vi.mock('#util/middlewares', () => ({
requestLoggerMiddleware: (_req: unknown, _res: unknown, next: () => void) =>
@@ -14,12 +15,17 @@ vi.mock('#util/middlewares', () => ({
vi.mock('./services/gocardless-service', () => ({
goCardlessService: {
createRequisition: vi.fn(),
+ setToken: vi.fn(),
+ getInstitutions: vi.fn(),
isConfigured: vi.fn(() => true),
},
}));
const { goCardlessService } = await import('./services/gocardless-service');
const { handlers } = await import('./app-gocardless');
+const { GoCardlessApiError } = await import('./services/gocardless-api');
+const { AccessDeniedError, RateLimitError, InvalidInputDataError } =
+ await import('./errors');
const app = express();
app.use(express.json());
@@ -108,6 +114,112 @@ describe('/create-web-token', () => {
});
});
+describe('/get-banks', () => {
+ const setToken = vi.mocked(goCardlessService.setToken);
+ const getInstitutions = vi.mocked(goCardlessService.getInstitutions);
+
+ function apiError(status: number, data?: unknown) {
+ const error = new GoCardlessApiError(
+ `GoCardless API error: ${status}`,
+ status,
+ {},
+ );
+ error.response.data = data;
+ return error;
+ }
+
+ beforeEach(() => {
+ setToken.mockReset();
+ setToken.mockResolvedValue(undefined);
+ getInstitutions.mockReset();
+ });
+
+ it('surfaces the reason GoCardless denied the request', async () => {
+ getInstitutions.mockRejectedValue(
+ new AccessDeniedError(
+ apiError(403, {
+ summary: 'IP address access denied',
+ detail:
+ "Your IP 203.0.113.7 isn't whitelisted to perform this action",
+ status_code: 403,
+ }),
+ ),
+ );
+
+ const res = await request(app).post('/get-banks').send({ country: 'GB' });
+
+ expect(res.body.data).toEqual({
+ error_code: 'INTERNAL_ERROR',
+ error_type: 'IP address access denied',
+ error_details: {
+ status: 403,
+ summary: 'IP address access denied',
+ detail: "Your IP 203.0.113.7 isn't whitelisted to perform this action",
+ },
+ });
+ });
+
+ it('surfaces the reason GoCardless rate limited the request', async () => {
+ getInstitutions.mockRejectedValue(
+ new RateLimitError(
+ apiError(429, {
+ summary: 'Rate limit exceeded',
+ detail: 'The rate limit for this resource is 4/day',
+ }),
+ ),
+ );
+
+ const res = await request(app).post('/get-banks').send({ country: 'GB' });
+
+ expect(res.body.data.error_details).toEqual({
+ status: 429,
+ summary: 'Rate limit exceeded',
+ detail: 'The rate limit for this resource is 4/day',
+ });
+ });
+
+ it('surfaces the field GoCardless rejected on a 400', async () => {
+ getInstitutions.mockRejectedValue(
+ new InvalidInputDataError(
+ apiError(400, {
+ country: {
+ summary: 'Invalid country choice.',
+ detail: '"ZZ" is not a valid choice.',
+ },
+ }),
+ ),
+ );
+
+ const res = await request(app).post('/get-banks').send({ country: 'ZZ' });
+
+ expect(res.body.data.error_details).toEqual({
+ status: 400,
+ summary: 'Invalid country choice.',
+ detail: '"ZZ" is not a valid choice.',
+ });
+ });
+
+ it('omits error_details for failures that did not come from GoCardless', async () => {
+ getInstitutions.mockRejectedValue(new Error('socket hang up'));
+
+ const res = await request(app).post('/get-banks').send({ country: 'GB' });
+
+ expect(res.body.data).toEqual({
+ error_code: 'INTERNAL_ERROR',
+ error_type: 'socket hang up',
+ });
+ });
+
+ it('still returns the bank list on success', async () => {
+ getInstitutions.mockResolvedValue([mockInstitution]);
+
+ const res = await request(app).post('/get-banks').send({ country: 'GB' });
+
+ expect(res.body.status).toBe('ok');
+ expect(res.body.data).toEqual([mockInstitution]);
+ });
+});
+
describe('/link', () => {
it('serves the completion page', async () => {
const res = await request(app).get('/link');
diff --git a/packages/sync-server/src/app-gocardless/util/gocardless-error-details.test.ts b/packages/sync-server/src/app-gocardless/util/gocardless-error-details.test.ts
new file mode 100644
index 0000000000..78d91809a2
--- /dev/null
+++ b/packages/sync-server/src/app-gocardless/util/gocardless-error-details.test.ts
@@ -0,0 +1,141 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ AccessDeniedError,
+ GenericGoCardlessError,
+ InvalidInputDataError,
+ RateLimitError,
+} from '#app-gocardless/errors';
+import { GoCardlessApiError } from '#app-gocardless/services/gocardless-api';
+
+import { getGoCardlessErrorDetails } from './gocardless-error-details';
+
+function apiError(status: number, data?: unknown) {
+ const error = new GoCardlessApiError(
+ `GoCardless API error: ${status}`,
+ status,
+ {},
+ );
+ error.response.data = data;
+ return error;
+}
+
+describe('getGoCardlessErrorDetails', () => {
+ it('reads summary and detail off a typed client error', () => {
+ const error = new AccessDeniedError(
+ apiError(403, {
+ summary: 'IP address access denied',
+ detail: "Your IP 203.0.113.7 isn't whitelisted to perform this action",
+ status_code: 403,
+ }),
+ );
+
+ expect(getGoCardlessErrorDetails(error)).toEqual({
+ status: 403,
+ summary: 'IP address access denied',
+ detail: "Your IP 203.0.113.7 isn't whitelisted to perform this action",
+ });
+ });
+
+ it('reads a bare GoCardlessApiError', () => {
+ const error = apiError(429, {
+ summary: 'Rate limit exceeded',
+ detail: 'The rate limit for this resource is 4/day',
+ });
+
+ expect(getGoCardlessErrorDetails(error)).toEqual({
+ status: 429,
+ summary: 'Rate limit exceeded',
+ detail: 'The rate limit for this resource is 4/day',
+ });
+ });
+
+ it('reads the first nested field error GoCardless returns for a 400', () => {
+ const error = new InvalidInputDataError(
+ apiError(400, {
+ country: {
+ summary: 'Invalid country choice.',
+ detail: '"ZZ" is not a valid choice.',
+ },
+ }),
+ );
+
+ expect(getGoCardlessErrorDetails(error)).toEqual({
+ status: 400,
+ summary: 'Invalid country choice.',
+ detail: '"ZZ" is not a valid choice.',
+ });
+ });
+
+ it('reads the GoCardless response wrapped by GenericGoCardlessError', () => {
+ const error = new GenericGoCardlessError(
+ apiError(502, {
+ summary: 'Institution service unavailable',
+ detail: 'The institution is temporarily unavailable',
+ }),
+ );
+
+ expect(getGoCardlessErrorDetails(error)).toEqual({
+ status: 502,
+ summary: 'Institution service unavailable',
+ detail: 'The institution is temporarily unavailable',
+ });
+ });
+
+ it('ignores details that did not come from a GoCardless response', () => {
+ const error = new GenericGoCardlessError({
+ summary: 'Not from GoCardless',
+ detail: 'Must not reach the client',
+ });
+
+ expect(getGoCardlessErrorDetails(error)).toBeUndefined();
+ });
+
+ it('keeps the status when GoCardless sent no parseable body', () => {
+ expect(
+ getGoCardlessErrorDetails(new RateLimitError(apiError(429))),
+ ).toEqual({
+ status: 429,
+ });
+ });
+
+ it('returns undefined for errors unrelated to the GoCardless API', () => {
+ expect(getGoCardlessErrorDetails(new Error('boom'))).toBeUndefined();
+ expect(getGoCardlessErrorDetails(undefined)).toBeUndefined();
+ });
+
+ it('ignores non-string summary and detail values', () => {
+ const error = new AccessDeniedError(
+ apiError(403, { summary: { nested: true }, detail: 42 }),
+ );
+
+ expect(getGoCardlessErrorDetails(error)).toEqual({ status: 403 });
+ });
+
+ it('truncates overlong values so a stray HTML body cannot flood the UI', () => {
+ const error = new AccessDeniedError(
+ apiError(403, { summary: 'a'.repeat(1000), detail: 'b'.repeat(1000) }),
+ );
+
+ const details = getGoCardlessErrorDetails(error);
+
+ expect(details?.summary).toHaveLength(500);
+ expect(details?.detail).toHaveLength(500);
+ });
+
+ it('does not surface credentials or headers from the error', () => {
+ const error = apiError(401, {
+ summary: 'Invalid token',
+ detail: 'Token is invalid or expired',
+ secret_id: 'super-secret-id',
+ secret_key: 'super-secret-key',
+ });
+ error.response.headers = { authorization: 'Bearer super-secret-token' };
+
+ expect(getGoCardlessErrorDetails(error)).toEqual({
+ status: 401,
+ summary: 'Invalid token',
+ detail: 'Token is invalid or expired',
+ });
+ });
+});
diff --git a/packages/sync-server/src/app-gocardless/util/gocardless-error-details.ts b/packages/sync-server/src/app-gocardless/util/gocardless-error-details.ts
new file mode 100644
index 0000000000..70b96b6b78
--- /dev/null
+++ b/packages/sync-server/src/app-gocardless/util/gocardless-error-details.ts
@@ -0,0 +1,103 @@
+import { GoCardlessApiError } from '#app-gocardless/services/gocardless-api';
+
+/**
+ * The part of a GoCardless failure that is safe to hand back to the client.
+ * Deliberately a whitelist: GoCardless error bodies are echoed back to the
+ * browser, so only the human-readable fields and the HTTP status travel, never
+ * the raw body or the request headers (which carry our bearer token).
+ */
+export type GoCardlessErrorDetails = {
+ status?: number;
+ summary?: string;
+ detail?: string;
+};
+
+const MAX_TEXT_LENGTH = 500;
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+function readText(value: unknown): string | undefined {
+ if (typeof value !== 'string') {
+ return undefined;
+ }
+
+ const trimmed = value.trim();
+ return trimmed ? trimmed.slice(0, MAX_TEXT_LENGTH) : undefined;
+}
+
+function readSummaryAndDetail(value: unknown): GoCardlessErrorDetails {
+ if (!isRecord(value)) {
+ return {};
+ }
+
+ const summary = readText(value.summary);
+ const detail = readText(value.detail);
+
+ return {
+ ...(summary ? { summary } : {}),
+ ...(detail ? { detail } : {}),
+ };
+}
+
+/**
+ * GoCardless answers either with a flat `{ summary, detail }` body or, for
+ * validation failures, with one such object per rejected field
+ * (`{ country: { summary, detail } }`). Only the first rejected field is
+ * reported — it is enough to tell the user what to correct.
+ */
+function readErrorBody(body: unknown): GoCardlessErrorDetails {
+ const flat = readSummaryAndDetail(body);
+ if (flat.summary || flat.detail) {
+ return flat;
+ }
+
+ if (!isRecord(body)) {
+ return {};
+ }
+
+ for (const value of Object.values(body)) {
+ const nested = readSummaryAndDetail(value);
+ if (nested.summary || nested.detail) {
+ return nested;
+ }
+ }
+
+ return {};
+}
+
+function findApiError(error: unknown): GoCardlessApiError | undefined {
+ if (error instanceof GoCardlessApiError) {
+ return error;
+ }
+
+ if (error instanceof Error && 'details' in error) {
+ const { details } = error as { details: unknown };
+ if (details instanceof GoCardlessApiError) {
+ return details;
+ }
+ }
+
+ return undefined;
+}
+
+/**
+ * Pulls the reason GoCardless rejected a request out of whatever error the
+ * service layer threw, so it can be surfaced in the UI instead of being
+ * collapsed into a generic message. Returns `undefined` for failures that did
+ * not come from the GoCardless API.
+ */
+export function getGoCardlessErrorDetails(
+ error: unknown,
+): GoCardlessErrorDetails | undefined {
+ const apiError = findApiError(error);
+ if (!apiError) {
+ return undefined;
+ }
+
+ return {
+ status: apiError.response.status,
+ ...readErrorBody(apiError.response.data),
+ };
+}
diff --git a/packages/sync-server/src/app-gocardless/util/handle-error.ts b/packages/sync-server/src/app-gocardless/util/handle-error.ts
index c1c7efb05e..2107a71113 100644
--- a/packages/sync-server/src/app-gocardless/util/handle-error.ts
+++ b/packages/sync-server/src/app-gocardless/util/handle-error.ts
@@ -1,6 +1,8 @@
import createDebug from 'debug';
import type { Request, Response } from 'express';
+import { getGoCardlessErrorDetails } from './gocardless-error-details';
+
const debugSensitive = createDebug('actual-sensitive:bank-sync');
export function handleError(
@@ -15,11 +17,13 @@ export function handleError(
req.baseUrl + req.path,
err,
);
+ const errorDetails = getGoCardlessErrorDetails(err);
res.send({
status: 'ok',
data: {
error_code: 'INTERNAL_ERROR',
error_type: err.message ? err.message : 'internal-error',
+ ...(errorDetails ? { error_details: errorDetails } : {}),
},
});
});
diff --git a/upcoming-release-notes/gocardless-surface-error-reason.md b/upcoming-release-notes/gocardless-surface-error-reason.md
new file mode 100644
index 0000000000..5d9b2e2e18
--- /dev/null
+++ b/upcoming-release-notes/gocardless-surface-error-reason.md
@@ -0,0 +1,6 @@
+---
+category: Enhancements
+authors: [zannis]
+---
+
+Show the reason GoCardless rejected a request (such as an IP block or a rate limit) when loading the bank list fails, instead of always blaming misconfigured credentials.