Skip to content

The open-source agent harness - the runtime layer that turns an LLM into a working agent.

Implement centralized error handling with getErrorMessage utility (#149)

Govinda Vashishtha26d203a7c025
diff --git a/packages/frontend/src/App.tsx b/packages/frontend/src/App.tsx
index 435a75269..cba81477a 100644
--- a/packages/frontend/src/App.tsx
+++ b/packages/frontend/src/App.tsx
@@ -1,4 +1,4 @@
-import { createTrueFoundryServer, TrueforgeUI, type SlotOverrides } from '@truefoundry/trueforge-ui';
+import { createTrueFoundryServer, getErrorMessage, TrueforgeUI, type SlotOverrides } from '@truefoundry/trueforge-ui';
import { useEffect, useMemo, useState } from 'react';
import { AuthErrorScreen } from './AuthErrorScreen';
import { probeSession, type SessionState } from './authSession';
@@ -93,7 +93,7 @@ export function App() {
if (!state.cancelled) {
setBoot({
status: 'error',
- message: err instanceof Error ? err.message : 'Failed to boot',
+ message: getErrorMessage(err, 'Failed to boot'),
});
}
}
diff --git a/packages/trueforge-ui-sdk/src/atoms/SaveAgentButton.tsx b/packages/trueforge-ui-sdk/src/atoms/SaveAgentButton.tsx
index 07b1ed7b4..cdc82af1f 100644
--- a/packages/trueforge-ui-sdk/src/atoms/SaveAgentButton.tsx
+++ b/packages/trueforge-ui-sdk/src/atoms/SaveAgentButton.tsx
@@ -6,6 +6,7 @@ import { useId, useState, type FormEvent } from 'react';
import { useOptionalServer } from '../server/ServerContext.js';
import { useOptionalShellMode } from '../server/ShellModeContext.js';
import type { AgentSpec } from '../server/types.js';
+import { getErrorMessage } from '../utils/getErrorMessage.js';
import { auiButtonClass } from './lib/buttonClasses.js';
import { CenteredModal } from './primitives/CenteredModal.js';
@@ -75,7 +76,7 @@ export function SaveAgentButton() {
shell.invalidateAgentsList();
handleOpenChange(false);
} catch (err: unknown) {
- setError(err instanceof Error ? err.message : isUpdate ? 'Failed to update agent.' : 'Failed to save agent.');
+ setError(getErrorMessage(err, isUpdate ? 'Failed to update agent.' : 'Failed to save agent.'));
setSaving(false);
}
};
diff --git a/packages/trueforge-ui-sdk/src/atoms/draft/DraftCatalogProvider.tsx b/packages/trueforge-ui-sdk/src/atoms/draft/DraftCatalogProvider.tsx
index a7dac302f..f582d5adf 100644
--- a/packages/trueforge-ui-sdk/src/atoms/draft/DraftCatalogProvider.tsx
+++ b/packages/trueforge-ui-sdk/src/atoms/draft/DraftCatalogProvider.tsx
@@ -4,6 +4,7 @@ import { createContext, useCallback, useContext, useEffect, useMemo, useState, t
import { useOptionalServer } from '../../server/ServerContext.js';
import type { AgentSkill, ConnectorState, ModelSelection } from '../../server/types.js';
+import { getErrorMessage } from '../../utils/getErrorMessage.js';
type DraftCatalogValue = {
models: ModelSelection[];
@@ -37,17 +38,27 @@ export function DraftCatalogProvider({ children }: { children: ReactNode }) {
let cancelled = false;
setLoading(true);
setError(null);
- void Promise.all([server.getModels(), server.getSkills(), server.getMcp()])
- .then(([nextModels, nextSkills, nextMcp]) => {
+ // Settle each list alone so one failing picker does not blank the others.
+ void Promise.allSettled([server.getModels(), server.getSkills(), server.getMcp()])
+ .then(([modelsResult, skillsResult, mcpResult]) => {
if (cancelled) return;
- setModels(nextModels);
- setSkills(nextSkills);
- setConnectors(nextMcp);
- })
- .catch((err: unknown) => {
- if (!cancelled) {
- setError(err instanceof Error ? err.message : 'Failed to load catalog.');
+ const errors: string[] = [];
+ if (modelsResult.status === 'fulfilled') {
+ setModels(modelsResult.value);
+ } else {
+ errors.push(getErrorMessage(modelsResult.reason, 'Failed to load models.'));
+ }
+ if (skillsResult.status === 'fulfilled') {
+ setSkills(skillsResult.value);
+ } else {
+ errors.push(getErrorMessage(skillsResult.reason, 'Failed to load skills.'));
+ }
+ if (mcpResult.status === 'fulfilled') {
+ setConnectors(mcpResult.value);
+ } else {
+ errors.push(getErrorMessage(mcpResult.reason, 'Failed to load connectors.'));
}
+ setError(errors[0] ?? null);
})
.finally(() => {
if (!cancelled) setLoading(false);
diff --git a/packages/trueforge-ui-sdk/src/atoms/lib/useSearchAgentsList.ts b/packages/trueforge-ui-sdk/src/atoms/lib/useSearchAgentsList.ts
index ec91b9cf8..acda757f1 100644
--- a/packages/trueforge-ui-sdk/src/atoms/lib/useSearchAgentsList.ts
+++ b/packages/trueforge-ui-sdk/src/atoms/lib/useSearchAgentsList.ts
@@ -4,6 +4,7 @@ import { useCallback, useEffect, useRef, useState } from 'react';
import { useOptionalServer } from '../../server/ServerContext.js';
import type { AgentLibraryEntry } from '../../server/types.js';
+import { getErrorMessage } from '../../utils/getErrorMessage.js';
import { useDebouncedValue } from './useDebouncedValue.js';
export const SEARCH_AGENTS_PAGE_SIZE = 50;
@@ -97,7 +98,7 @@ export function useSearchAgentsList({
if (gen !== genRef.current) return;
setAgents([]);
setHasMore(false);
- setError(err instanceof Error ? err.message : 'Failed to load agents.');
+ setError(getErrorMessage(err, 'Failed to load agents.'));
})
.finally(() => {
if (gen === genRef.current) setLoading(false);
diff --git a/packages/trueforge-ui-sdk/src/containers/ErrorToasterContainer.tsx b/packages/trueforge-ui-sdk/src/containers/ErrorToasterContainer.tsx
index 61da63c03..d6fbf1330 100644
--- a/packages/trueforge-ui-sdk/src/containers/ErrorToasterContainer.tsx
+++ b/packages/trueforge-ui-sdk/src/containers/ErrorToasterContainer.tsx
@@ -3,6 +3,7 @@
import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from 'react';
import { useSlot } from '../theme/SlotsProvider.js';
+import { getErrorMessage } from '../utils/getErrorMessage.js';
const MAX_TOAST_DESCRIPTION_CHARS = 480;
const MAX_VISIBLE_TOASTS = 5;
@@ -26,16 +27,6 @@ function truncateDescription(text: string): string {
return `${text.slice(0, MAX_TOAST_DESCRIPTION_CHARS - 1)}…`;
}
-function formatErrorBody(body: unknown): string | undefined {
- if (body == null) return undefined;
- if (typeof body === 'string') return body;
- try {
- return JSON.stringify(body, null, 2);
- } catch {
- return String(body);
- }
-}
-
function isHttpLikeError(error: unknown): error is Error & { statusCode?: number; body?: unknown } {
return error instanceof Error && ('statusCode' in error || 'body' in error);
}
@@ -45,21 +36,14 @@ function normalizeError(error: unknown): ErrorToastContent {
const statusCode = error.statusCode;
if (statusCode != null || error.body != null) {
const title = statusCode != null ? `Request failed (${statusCode})` : 'Request failed';
- const raw = formatErrorBody(error.body) ?? (error.message || 'The server returned an error.');
+ const raw = getErrorMessage(error, 'The server returned an error.');
return { title, description: truncateDescription(raw) };
}
}
- if (error instanceof Error) {
- return {
- title: 'Something went wrong',
- description: truncateDescription(error.message || 'An unexpected error occurred.'),
- };
- }
-
return {
title: 'Something went wrong',
- description: truncateDescription(String(error)),
+ description: truncateDescription(getErrorMessage(error, 'An unexpected error occurred.')),
};
}
diff --git a/packages/trueforge-ui-sdk/src/containers/SettingsBuilder/ConnectorDetails.tsx b/packages/trueforge-ui-sdk/src/containers/SettingsBuilder/ConnectorDetails.tsx
index 8e29f605f..e1478e3b0 100644
--- a/packages/trueforge-ui-sdk/src/containers/SettingsBuilder/ConnectorDetails.tsx
+++ b/packages/trueforge-ui-sdk/src/containers/SettingsBuilder/ConnectorDetails.tsx
@@ -6,6 +6,7 @@ import { Button } from '../../atoms/primitives/Button.js';
import { Icon } from '../../icons/Icon.js';
import { useCatalogServer } from '../../server/ServerContext.js';
import type { ConnectorBase, ToolBase } from '../../server/types.js';
+import { getErrorMessage } from '../../utils/getErrorMessage.js';
import { AUTH_TYPE_LABELS } from './authTypeLabels.js';
type ConnectorDetailsProps = {
@@ -34,7 +35,7 @@ const ConnectorDetails = ({ connector, onBack, onDisconnect, busy = false }: Con
})
.catch((err: unknown) => {
if (!cancelled) {
- setToolsError(err instanceof Error ? err.message : 'Failed to load connector tools');
+ setToolsError(getErrorMessage(err, 'Failed to load connector tools'));
}
})
.finally(() => {
diff --git a/packages/trueforge-ui-sdk/src/containers/SettingsBuilder/ConnectorSettings.tsx b/packages/trueforge-ui-sdk/src/containers/SettingsBuilder/ConnectorSettings.tsx
index 2ac237df6..a621230a5 100644
--- a/packages/trueforge-ui-sdk/src/containers/SettingsBuilder/ConnectorSettings.tsx
+++ b/packages/trueforge-ui-sdk/src/containers/SettingsBuilder/ConnectorSettings.tsx
@@ -9,6 +9,7 @@ import { useMCPAuth } from '@/hooks/useMcpAuth.js';
import { Icon } from '@/icons/Icon.js';
import { useCatalogServer } from '@/server/ServerContext.js';
import type { ConnectorAuth, ConnectorBase, ConnectorCatalogEntry } from '@/server/types.js';
+import { getErrorMessage } from '@/utils/getErrorMessage.js';
import AddMcpServerForm, { type AddMcpServerDraft } from './AddMcpServerForm.js';
import { AUTH_TYPE_LABELS } from './authTypeLabels.js';
import ConnectorDetails from './ConnectorDetails.js';
@@ -75,7 +76,7 @@ const ConnectorSettings = () => {
});
setSelectedConnector(current => (current ? (listed.find(item => item.id === current.id) ?? null) : null));
} catch (err) {
- setError(err instanceof Error ? err.message : 'Failed to load connectors');
+ setError(getErrorMessage(err, 'Failed to load connectors'));
} finally {
setLoading(false);
}
@@ -127,7 +128,7 @@ const ConnectorSettings = () => {
await fn();
await refresh();
} catch (err) {
- setError(err instanceof Error ? err.message : 'Request failed');
+ setError(getErrorMessage(err, 'Request failed'));
throw err;
} finally {
setBusy(false);
@@ -152,7 +153,7 @@ const ConnectorSettings = () => {
});
})
.catch(err => {
- setError(err instanceof Error ? err.message : 'Failed to load connector');
+ setError(getErrorMessage(err, 'Failed to load connector'));
});
}
});
diff --git a/packages/trueforge-ui-sdk/src/containers/SettingsBuilder/ModelSettings.tsx b/packages/trueforge-ui-sdk/src/containers/SettingsBuilder/ModelSettings.tsx
index bb9d8e516..ba606c346 100644
--- a/packages/trueforge-ui-sdk/src/containers/SettingsBuilder/ModelSettings.tsx
+++ b/packages/trueforge-ui-sdk/src/containers/SettingsBuilder/ModelSettings.tsx
@@ -7,6 +7,7 @@ import SearchInput from '../../atoms/primitives/SearchInput.js';
import { Icon } from '../../icons/Icon.js';
import { useCatalogServer } from '../../server/ServerContext.js';
import type { ModelEntry, ModelProviderBase, ModelProviderCatalogEntry } from '../../server/types.js';
+import { getErrorMessage } from '../../utils/getErrorMessage.js';
import { useErrorToasterOptional } from '../ErrorToasterContainer.js';
import CustomModelProviderForm, { type CustomProviderDraft } from './CustomModelProviderForm.js';
@@ -49,7 +50,7 @@ const ModelSettings = () => {
setConfigured(listed);
setCatalog(available);
} catch (err) {
- setError(err instanceof Error ? err.message : 'Failed to load model providers');
+ setError(getErrorMessage(err, 'Failed to load model providers'));
} finally {
setLoading(false);
}
@@ -118,7 +119,7 @@ const ModelSettings = () => {
if (toaster != null) {
toaster.showError(err);
} else {
- setError(err instanceof Error ? err.message : 'Request failed');
+ setError(getErrorMessage(err, 'Request failed'));
}
throw err;
} finally {
diff --git a/packages/trueforge-ui-sdk/src/containers/SettingsBuilder/SandboxSettings.tsx b/packages/trueforge-ui-sdk/src/containers/SettingsBuilder/SandboxSettings.tsx
index 218f5f0bd..1835c7dd4 100644
--- a/packages/trueforge-ui-sdk/src/containers/SettingsBuilder/SandboxSettings.tsx
+++ b/packages/trueforge-ui-sdk/src/containers/SettingsBuilder/SandboxSettings.tsx
@@ -6,6 +6,7 @@ import { Button } from '../../atoms/primitives/Button.js';
import { Icon } from '../../icons/Icon.js';
import { useCatalogServer } from '../../server/ServerContext.js';
import type { SandboxProviderBase, SandboxProviderCatalogEntry, SandboxProviderConfig } from '../../server/types.js';
+import { getErrorMessage } from '../../utils/getErrorMessage.js';
import ConfigureSandboxForm, { type SandboxConfigDraft } from './ConfigureSandboxForm.js';
const configFrom = ({
@@ -47,7 +48,7 @@ const SandboxSettings = () => {
setProviders(listed);
setCatalog(available);
} catch (err) {
- setError(err instanceof Error ? err.message : 'Failed to load sandbox providers');
+ setError(getErrorMessage(err, 'Failed to load sandbox providers'));
} finally {
if (!quiet) setLoading(false);
}
@@ -83,7 +84,7 @@ const SandboxSettings = () => {
await fn();
await refresh({ quiet: true });
} catch (err) {
- setError(err instanceof Error ? err.message : 'Request failed');
+ setError(getErrorMessage(err, 'Request failed'));
throw err;
} finally {
setBusy(false);
diff --git a/packages/trueforge-ui-sdk/src/containers/SettingsBuilder/SkillSettings.tsx b/packages/trueforge-ui-sdk/src/containers/SettingsBuilder/SkillSettings.tsx
index bf712e784..4ddbf7c83 100644
--- a/packages/trueforge-ui-sdk/src/containers/SettingsBuilder/SkillSettings.tsx
+++ b/packages/trueforge-ui-sdk/src/containers/SettingsBuilder/SkillSettings.tsx
@@ -7,6 +7,7 @@ import SearchInput from '@/atoms/primitives/SearchInput.js';
import { Icon } from '@/icons/Icon.js';
import { useCatalogServer } from '../../server/ServerContext.js';
import type { RegistrySkill, SkillBase, SkillCatalogEntry, SkillConfigBase } from '../../server/types.js';
+import { getErrorMessage } from '../../utils/getErrorMessage.js';
import ImportGithubSkillForm from './ImportGithubSkillForm.js';
const matchesQuery = (query: string, name: string, description: string) =>
@@ -34,7 +35,7 @@ const SkillSettings = () => {
setSkills(defined);
setCatalog(available);
} catch (err) {
- setError(err instanceof Error ? err.message : 'Failed to load skills');
+ setError(getErrorMessage(err, 'Failed to load skills'));
} finally {
setLoading(false);
}
@@ -65,7 +66,7 @@ const SkillSettings = () => {
await fn();
await refresh();
} catch (err) {
- setError(err instanceof Error ? err.message : 'Request failed');
+ setError(getErrorMessage(err, 'Request failed'));
throw err;
} finally {
setBusy(false);
diff --git a/packages/trueforge-ui-sdk/src/containers/TrueforgeUI.tsx b/packages/trueforge-ui-sdk/src/containers/TrueforgeUI.tsx
index ef96a17c8..2d9dbc56a 100644
--- a/packages/trueforge-ui-sdk/src/containers/TrueforgeUI.tsx
+++ b/packages/trueforge-ui-sdk/src/containers/TrueforgeUI.tsx
@@ -10,6 +10,7 @@ import { DEFAULT_AGENT_CONFIG, ShellModeProvider, useShellMode, type AgentConfig
import type { TrueforgeServerConfig } from '../server/TrueforgeServerConfig.js';
import { SlotsProvider, type SlotOverrides } from '../theme/SlotsProvider.js';
import type { LayoutProp, ThemeConfig } from '../theme/types.js';
+import { getErrorMessage } from '../utils/getErrorMessage.js';
import PostMcpOauthScreen from './McpOauthContainer/PostMcpOauthScreen.js';
import { TrueFoundryChatProvider, type TrueFoundryChatProviderProps } from './TrueFoundryChatProvider.js';
import { useResolvedServer } from './useResolvedServer.js';
@@ -80,7 +81,7 @@ function ServerInitLoader({ className }: { className?: string }) {
}
function ServerInitError({ error, className }: { error: unknown; className?: string }) {
- const message = error instanceof Error ? error.message : 'Failed to initialize server';
+ const message = getErrorMessage(error, 'Failed to initialize server');
return (
<div
role="alert"
diff --git a/packages/trueforge-ui-sdk/src/index.ts b/packages/trueforge-ui-sdk/src/index.ts
index 4367a4c87..1aaaecfb0 100644
--- a/packages/trueforge-ui-sdk/src/index.ts
+++ b/packages/trueforge-ui-sdk/src/index.ts
@@ -327,6 +327,7 @@ export type {
// Utils
export { computeAgentStepsSplit } from './utils/computeAgentStepsSplit.js';
export type { AgentStepPart, AgentStepsSplitResult } from './utils/computeAgentStepsSplit.js';
+export { getErrorMessage } from './utils/getErrorMessage.js';
export { AgentsLibrary } from './atoms/AgentsLibrary.js';
export type { AgentsLibraryProps } from './atoms/AgentsLibrary.js';
diff --git a/packages/trueforge-ui-sdk/src/utils/getErrorMessage.ts b/packages/trueforge-ui-sdk/src/utils/getErrorMessage.ts
new file mode 100644
index 000000000..cdefad293
--- /dev/null
+++ b/packages/trueforge-ui-sdk/src/utils/getErrorMessage.ts
@@ -0,0 +1,65 @@
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return value != null && typeof value === 'object';
+}
+
+function readNonEmptyString(value: unknown): string | undefined {
+ return typeof value === 'string' && value.trim() !== '' ? value : undefined;
+}
+
+/**
+ * Reads a display string from API-shaped errors: `message`, then nested
+ * `error.message`. When neither exists, stringifies the value.
+ */
+function messageFromErrorShaped(value: unknown): string | undefined {
+ if (!isRecord(value)) return undefined;
+ const direct = readNonEmptyString(value.message);
+ if (direct != null) return direct;
+ if (isRecord(value.error)) {
+ return readNonEmptyString(value.error.message);
+ }
+ return undefined;
+}
+
+function stringifyError(error: unknown): string {
+ if (typeof error === 'string') return error;
+ if (isRecord(error)) {
+ try {
+ return JSON.stringify(error);
+ } catch {
+ return Object.prototype.toString.call(error);
+ }
+ }
+ return String(error);
+}
+
+/**
+ * User-facing error text. Prefers HTTP body `{ error: { message } }` when
+ * present (e.g. TrueForgeError), then `error.message` / `error.error.message`,
+ * then `fallback`, then a string form of the value.
+ */
+export function getErrorMessage(error: unknown, fallback?: string): string {
+ if (typeof error === 'string') {
+ const trimmed = error.trim();
+ if (trimmed !== '') return error;
+ return fallback ?? error;
+ }
+
+ if (isRecord(error) && 'body' in error) {
+ const fromBody = messageFromErrorShaped(error.body);
+ if (fromBody != null) return fromBody;
+ if (error.body != null) {
+ if (typeof error.body === 'string') {
+ const trimmed = error.body.trim();
+ if (trimmed !== '') return error.body;
+ } else {
+ return stringifyError(error.body);
+ }
+ }
+ }
+
+ const fromShape = messageFromErrorShaped(error);
+ if (fromShape != null) return fromShape;
+
+ if (fallback != null) return fallback;
+ return stringifyError(error);
+}
diff --git a/packages/trueforge-ui-sdk/test/atoms/draft/DraftCatalogProvider.test.tsx b/packages/trueforge-ui-sdk/test/atoms/draft/DraftCatalogProvider.test.tsx
index 70aa7fadb..bd088e886 100644
--- a/packages/trueforge-ui-sdk/test/atoms/draft/DraftCatalogProvider.test.tsx
+++ b/packages/trueforge-ui-sdk/test/atoms/draft/DraftCatalogProvider.test.tsx
@@ -122,4 +122,30 @@ describe('DraftCatalogProvider', () => {
expect(screen.getByTestId('loading')).toHaveTextContent('false');
expect(screen.getByTestId('models')).toBeEmptyDOMElement();
});
+
+ it('keeps successful lists when a sibling catalog call fails', async () => {
+ const server = createMockAgentUIServer({
+ getModels: async () => [{ name: 'openai/gpt-4.1', provider: 'OpenAI' }],
+ getSkills: async () => {
+ throw new Error('Skills unavailable');
+ },
+ getMcp: async () => [{ id: 'mcp-1', name: 'GitHub' }],
+ });
+
+ render(
+ <ServerProvider server={server}>
+ <DraftCatalogProvider>
+ <CatalogProbe />
+ </DraftCatalogProvider>
+ </ServerProvider>,
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: 'Load catalog' }));
+
+ await waitFor(() => expect(screen.getByTestId('loading')).toHaveTextContent('false'));
+ expect(screen.getByTestId('models')).toHaveTextContent('openai/gpt-4.1');
+ expect(screen.getByTestId('connectors')).toHaveTextContent('GitHub');
+ expect(screen.getByTestId('skills')).toBeEmptyDOMElement();
+ expect(screen.getByTestId('error')).toHaveTextContent('Skills unavailable');
+ });
});
diff --git a/packages/trueforge-ui-sdk/test/containers/ErrorToasterContainer.test.tsx b/packages/trueforge-ui-sdk/test/containers/ErrorToasterContainer.test.tsx
index ae23e897e..572b92652 100644
--- a/packages/trueforge-ui-sdk/test/containers/ErrorToasterContainer.test.tsx
+++ b/packages/trueforge-ui-sdk/test/containers/ErrorToasterContainer.test.tsx
@@ -96,7 +96,27 @@ describe('ErrorToasterProvider', () => {
fireEvent.click(screen.getByRole('button', { name: 'boom' }));
expect(await screen.findByText('Request failed (422)')).toBeInTheDocument();
- expect(screen.getByText(/"detail": "invalid agent"/)).toBeInTheDocument();
+ expect(screen.getByText(/"detail":"invalid agent"/)).toBeInTheDocument();
+ });
+
+ it('extracts nested error.message from HTTP body', async () => {
+ const httpError = Object.assign(new Error('Status code: 409'), {
+ statusCode: 409,
+ body: { error: { message: 'Name taken' } },
+ });
+
+ render(
+ <SlotsProvider>
+ <ErrorToasterProvider>
+ <Trigger errors={[httpError]} />
+ </ErrorToasterProvider>
+ </SlotsProvider>,
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: 'boom' }));
+
+ expect(await screen.findByText('Request failed (409)')).toBeInTheDocument();
+ expect(screen.getByText('Name taken')).toBeInTheDocument();
});
it('keeps only the five most recent errors visible', async () => {
diff --git a/packages/trueforge-ui-sdk/test/publicUiExports.test.ts b/packages/trueforge-ui-sdk/test/publicUiExports.test.ts
index 3b095cf68..f226003c7 100644
--- a/packages/trueforge-ui-sdk/test/publicUiExports.test.ts
+++ b/packages/trueforge-ui-sdk/test/publicUiExports.test.ts
@@ -102,6 +102,7 @@ const expectedRuntimeExports: Array<keyof typeof sdk> = [
'computeAgentStepsSplit',
'createTrueFoundryServer',
'defaultSlots',
+ 'getErrorMessage',
'libraryAgentId',
'mergeAgentSpec',
'preloadMarkdownOpenUI',
diff --git a/packages/trueforge-ui-sdk/test/utils/getErrorMessage.test.ts b/packages/trueforge-ui-sdk/test/utils/getErrorMessage.test.ts
new file mode 100644
index 000000000..707ea0b35
--- /dev/null
+++ b/packages/trueforge-ui-sdk/test/utils/getErrorMessage.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from 'vitest';
+
+import { getErrorMessage } from '@/utils/getErrorMessage.js';
+
+describe('getErrorMessage', () => {
+ it('prefers error.message', () => {
+ expect(getErrorMessage({ message: 'top', error: { message: 'nested' } })).toBe('top');
+ });
+
+ it('falls back to error.error.message', () => {
+ expect(getErrorMessage({ error: { message: 'nested' } })).toBe('nested');
+ });
+
+ it('prefers HTTP body error.message over the Error message', () => {
+ const err = Object.assign(new Error('Status code: 409\nBody: …'), {
+ statusCode: 409,
+ body: { error: { message: 'Name taken' } },
+ });
+ expect(getErrorMessage(err)).toBe('Name taken');
+ });
+
+ it('stringifies a non-message HTTP body', () => {
+ const err = Object.assign(new Error('request failed'), {
+ statusCode: 422,
+ body: { detail: 'invalid agent' },
+ });
+ expect(getErrorMessage(err)).toBe(JSON.stringify({ detail: 'invalid agent' }));
+ });
+
+ it('uses fallback when nothing is extractable', () => {
+ expect(getErrorMessage(undefined, 'fallback')).toBe('fallback');
+ expect(getErrorMessage(null, 'fallback')).toBe('fallback');
+ });
+
+ it('stringifies the value when both messages are missing and there is no fallback', () => {
+ expect(getErrorMessage({ code: 1 })).toBe(JSON.stringify({ code: 1 }));
+ });
+
+ it('reads plain Error.message', () => {
+ expect(getErrorMessage(new Error('boom'), 'fallback')).toBe('boom');
+ });
+});