:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(workflows): surface API error bodies in account action logs (#69429)
Arthur Moreira de Deus6aa1fcf89558
diff --git a/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/api-error.ts b/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/api-error.tsnew file mode 100644index 000000000000..4708e453bb80--- /dev/null+++ b/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/api-error.ts@@ -0,0 +1,3 @@+export const hogApiErrorMessageFn = `fun apiErrorMessage(response) {+ return response.body.error ?? response.body.detail ?? response.body+}`diff --git a/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-accounts.template.test.ts b/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-accounts.template.test.tsnew file mode 100644index 000000000000..5004956ed441--- /dev/null+++ b/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-accounts.template.test.ts@@ -0,0 +1,89 @@+import { TemplateTester } from '../../test/test-helpers'+import { template as getAccountTemplate } from './posthog-get-account.template'+import { template as updateAccountPropertyTemplate } from './posthog-update-account-property.template'+import { template as updateAccountTemplate } from './posthog-update-account.template'++describe('posthog customer analytics account templates', () => {+ const cases = [+ {+ name: 'get account',+ template: getAccountTemplate,+ inputs: { external_id: 'acme-1' },+ failurePrefix: 'Failed to fetch account (400):',+ successLog: 'Fetched account acme-1',+ },+ {+ name: 'update account',+ template: updateAccountTemplate,+ inputs: { external_id: 'acme-1', tags: ['vip'], tags_mode: 'add' },+ failurePrefix: 'Failed to update account (400):',+ successLog: 'Updated account acme-1',+ },+ {+ name: 'update account property',+ template: updateAccountPropertyTemplate,+ inputs: { external_id: 'acme-1', properties: { '0197f9f0-0000-0000-0000-000000000000': 42 } },+ failurePrefix: 'Failed to update account properties (400):',+ successLog: 'Updated custom properties on account acme-1',+ },+ ]++ describe.each(cases)('$name', ({ template, inputs, failurePrefix, successLog }) => {+ const tester = new TemplateTester(template)++ beforeEach(async () => {+ await tester.beforeEach()+ })++ it('surfaces the API error body when the request fails', async () => {+ let response = await tester.invoke(inputs)+ expect(response.error).toBeUndefined()+ expect(response.finished).toBe(false)++ response = await tester.invokeFetchResponse(response.invocation, {+ status: 400,+ body: { error: 'CSM: no relationship definition with this name' },+ })++ expect(response.error).toEqual(`${failurePrefix} CSM: no relationship definition with this name`)+ })++ it('prints a readable line on success', async () => {+ let response = await tester.invoke(inputs)+ expect(response.error).toBeUndefined()++ response = await tester.invokeFetchResponse(response.invocation, {+ status: 200,+ body: { id: 'account-id', external_id: 'acme-1' },+ })++ expect(response.error).toBeUndefined()+ expect(response.finished).toBe(true)+ expect(response.logs.filter((log) => log.level === 'info').map((log) => log.message)).toContain(successLog)+ })+ })++ describe('error body without an error field', () => {+ const tester = new TemplateTester(updateAccountTemplate)++ beforeEach(async () => {+ await tester.beforeEach()+ })++ it.each([+ [+ 'DRF-rendered error with a detail field',+ 429,+ { detail: 'Request was throttled.' },+ 'Failed to update account (429): Request was throttled.',+ ],+ ['non-JSON body', 503, 'upstream connect error', 'Failed to update account (503): upstream connect error'],+ ])('%s', async (_name, status, body, expected) => {+ let response = await tester.invoke({ external_id: 'acme-1', tags: ['vip'] })++ response = await tester.invokeFetchResponse(response.invocation, { status, body })++ expect(response.error).toEqual(expected)+ })+ })+})diff --git a/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-get-account.template.ts b/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-get-account.template.tsindex bc1d83f92205..40083e784654 100644--- a/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-get-account.template.ts+++ b/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-get-account.template.ts@@ -1,5 +1,7 @@import { HogFunctionTemplate } from '~/cdp/types'+import { hogApiErrorMessageFn } from './api-error'+export const template: HogFunctionTemplate = {free: true,status: 'hidden',@@ -11,6 +13,8 @@ export const template: HogFunctionTemplate = {category: ['Custom'],code_language: 'hog',code: `+${hogApiErrorMessageFn}+if (empty(inputs.external_id)) {throw Error('Account external ID is required')}@@ -22,9 +26,10 @@ if (response.status == 404) {}if (response.status != 200) {- throw Error(f'Failed to fetch account: {response.status}')+ throw Error(f'Failed to fetch account ({response.status}): {apiErrorMessage(response)}')}+print(f'Fetched account {inputs.external_id}')return response.body`,inputs_schema: [diff --git a/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-update-account-property.template.ts b/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-update-account-property.template.tsindex 08b61177e597..b6c662398384 100644--- a/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-update-account-property.template.ts+++ b/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-update-account-property.template.ts@@ -1,5 +1,7 @@import { HogFunctionTemplate } from '~/cdp/types'+import { hogApiErrorMessageFn } from './api-error'+export const template: HogFunctionTemplate = {free: true,status: 'hidden',@@ -11,6 +13,8 @@ export const template: HogFunctionTemplate = {category: ['Custom'],code_language: 'hog',code: `+${hogApiErrorMessageFn}+if (empty(inputs.external_id)) {throw Error('Account external ID is required')}@@ -25,9 +29,10 @@ if (response.status == 404) {}if (response.status >= 400) {- throw Error(f'Failed to update account properties: {response.status}')+ throw Error(f'Failed to update account properties ({response.status}): {apiErrorMessage(response)}')}+print(f'Updated custom properties on account {inputs.external_id}')return response.body`,inputs_schema: [diff --git a/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-update-account.template.ts b/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-update-account.template.tsindex cd2d0ce4198c..8c6176b083cb 100644--- a/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-update-account.template.ts+++ b/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-update-account.template.ts@@ -1,5 +1,7 @@import { HogFunctionTemplate } from '~/cdp/types'+import { hogApiErrorMessageFn } from './api-error'+export const template: HogFunctionTemplate = {free: true,status: 'hidden',@@ -11,6 +13,8 @@ export const template: HogFunctionTemplate = {category: ['Custom'],code_language: 'hog',code: `+${hogApiErrorMessageFn}+if (empty(inputs.external_id)) {throw Error('Account external ID is required')}@@ -49,9 +53,10 @@ if (response.status == 404) {}if (response.status >= 400) {- throw Error(f'Failed to update account: {response.status}')+ throw Error(f'Failed to update account ({response.status}): {apiErrorMessage(response)}')}+print(f'Updated account {inputs.external_id}')return response.body`,inputs_schema: [diff --git a/nodejs/src/cdp/templates/test/test-helpers.ts b/nodejs/src/cdp/templates/test/test-helpers.tsindex 9b8ed6746e74..9dcaee246c29 100644--- a/nodejs/src/cdp/templates/test/test-helpers.ts+++ b/nodejs/src/cdp/templates/test/test-helpers.ts@@ -175,6 +175,11 @@ export class TemplateTester {public mockFetch = jest.fn()public mockPrint = jest.fn()+ // Async functions (postHogGetAccount, postHogGetTicket, ...) resolve the team to read+ // its secret_api_token — stub it so templates built on them are testable.+ public mockTeamManager = {+ getTeam: jest.fn().mockResolvedValue({ id: 1, secret_api_token: 'test-secret-token' }),+ }constructor(private _template: HogFunctionTemplate) {this.template = {..._template,@@ -213,7 +218,7 @@ export class TemplateTester {fetchBackoffMaxMs: config.CDP_FETCH_BACKOFF_MAX_MS,selfLoopGuardMode: config.CDP_SELF_LOOP_GUARD_MODE,},- { teamManager: undefined as any, siteUrl: config.SITE_URL },+ { teamManager: this.mockTeamManager as any, siteUrl: config.SITE_URL },hogInputsService,emailService,recipientTokensService@@ -363,7 +368,7 @@ export class TemplateTester {async invokeFetchResponse(invocation: CyclotronJobInvocationHogFunction,- response: { status: number; body: Record<string, any> }+ response: { status: number; body: unknown }): Promise<CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction>> {const modifiedInvocation = cloneInvocation(invocation)