Skip to content

Commit bebf924

Browse files
committed
fix: improved ax generate error
1 parent 8420adb commit bebf924

File tree

3 files changed

+56
-10
lines changed

3 files changed

+56
-10
lines changed

package-lock.json

Lines changed: 7 additions & 7 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/ax/dsp/generate.test.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -634,6 +634,31 @@ describe('Error handling in AxGen', () => {
634634
}
635635
});
636636

637+
it('should serialize cause properly in JSON', async () => {
638+
const originalError = new Error('AI service failed');
639+
const ai = new AxMockAIService({
640+
features: { functions: false, streaming: false },
641+
chatResponse: () => Promise.reject(originalError),
642+
});
643+
644+
const gen = new AxGen<{ userQuestion: string }, { modelAnswer: string }>(
645+
signature
646+
);
647+
try {
648+
await gen.forward(ai, { userQuestion: 'test' });
649+
throw new Error('Test should have failed but did not.');
650+
} catch (e) {
651+
const error = e as Error;
652+
const serialized = JSON.parse(JSON.stringify(error));
653+
expect(serialized.name).toBe('AxGenerateError');
654+
expect(serialized.message).toBe('Generate failed: AI service failed');
655+
expect(serialized.cause).toBeDefined();
656+
expect(serialized.cause.name).toBe('Error');
657+
expect(serialized.cause.message).toBe('AI service failed');
658+
expect(serialized.details).toBeDefined();
659+
}
660+
});
661+
637662
it('should handle streaming errors gracefully', async () => {
638663
const originalError = new Error('Streaming failed mid-stream');
639664
// Create a stream that errors after first chunk

src/ax/dsp/generate.ts

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1492,6 +1492,23 @@ export class AxGenerateError extends Error {
14921492
(this as ErrorOptions).cause = options.cause;
14931493
}
14941494
}
1495+
1496+
toJSON(): Record<string, unknown> {
1497+
const cause = (this as ErrorOptions).cause;
1498+
return {
1499+
name: this.name,
1500+
message: this.message,
1501+
details: this.details,
1502+
cause: cause
1503+
? {
1504+
name: cause.name,
1505+
message: cause.message,
1506+
stack: cause.stack,
1507+
}
1508+
: undefined,
1509+
stack: this.stack,
1510+
};
1511+
}
14951512
}
14961513

14971514
function enhanceError(
@@ -1537,7 +1554,11 @@ function enhanceError(
15371554
};
15381555

15391556
// Return custom error with short message and details as object property
1540-
return new AxGenerateError('Generate failed', details, {
1541-
cause: originalError,
1542-
});
1557+
return new AxGenerateError(
1558+
`Generate failed: ${originalError.message}`,
1559+
details,
1560+
{
1561+
cause: originalError,
1562+
}
1563+
);
15431564
}

0 commit comments

Comments
 (0)