@devries-cameron20 / composio-1 / commits / 9ae791ab9
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Improve error handling to preserve stack traces for better tracebacks

Co-Authored-By: musthaq@composio.dev <musthu.gm@gmail.com>

Devin AI committed May 23, 2025 at 09:58 UTC 9ae791ab9c763443eb9911c22cdd9c622351dc61
5 files changed +100 -24
examples/error-handling-demo/src/index.ts new
+52
@@ -0,0 +1,52 @@
1 +import { Composio } from '@composio/core';
2 +import { ComposioError } from '@composio/core';
3 +
4 +async function level3() {
5 + throw new ComposioError('Level 3 error', {
6 + code: 'LEVEL_3_ERROR',
7 + cause: new Error('Original cause'),
8 + });
9 +}
10 +
11 +async function level2() {
12 + try {
13 + await level3();
14 + } catch (error) {
15 + throw new ComposioError('Level 2 error', {
16 + code: 'LEVEL_2_ERROR',
17 + cause: error,
18 + });
19 + }
20 +}
21 +
22 +async function level1() {
23 + try {
24 + await level2();
25 + } catch (error) {
26 + throw new ComposioError('Level 1 error', {
27 + code: 'LEVEL_1_ERROR',
28 + cause: error,
29 + });
30 + }
31 +}
32 +
33 +async function main() {
34 + try {
35 + const composio = new Composio({
36 + apiKey: 'test-api-key',
37 + });
38 +
39 + await level1();
40 + } catch (error) {
41 + if (error instanceof ComposioError) {
42 + error.prettyPrint(true);
43 +
44 + console.log('\n\nRaw stack trace:');
45 + console.log(error.stack);
46 + } else {
47 + console.error('Unexpected error:', error);
48 + }
49 + }
50 +}
51 +
52 +main().catch(console.error);
packages/core/src/errors/ComposioError.ts
+34 -6
@@ -76,6 +76,11 @@ export class ComposioError extends Error {
76 constructor(message: string, options: ComposioErrorOptions = {}) {
77 super(message);
78
79 + // Captures stack trace excluding the constructor frame first
80 + if (Error.captureStackTrace) {
81 + Error.captureStackTrace(this, this.constructor);
82 + }
83 +
84 // Process the status code - either from options or from the cause if it's a BadRequestError
85 const statusCode =
86 options.statusCode ||
@@ -89,15 +94,15 @@ export class ComposioError extends Error {
94 // Node.js by default shows all the properties of the error object, so we are doing it conditionally
95 this.definePropertyIfExists('statusCode', statusCode);
96 this.definePropertyIfExists('cause', options.cause);
92 - this.definePropertyIfExists('stack', options.stack);
97 +
98 + const combinedStack = options.cause instanceof Error
99 + ? ComposioError.combineStackTraces(options.cause.stack, this.stack)
100 + : options.stack || this.stack;
101 + this.definePropertyIfExists('stack', combinedStack);
102
103 if (options.meta && Object.keys(options.meta).length > 0) {
104 this.definePropertyIfExists('meta', options.meta);
105 }
97 - // Captures stack trace excluding the constructor frame
98 - if (Error.captureStackTrace) {
99 - Error.captureStackTrace(this, this.constructor);
100 - }
106 }
107
108 /**
@@ -116,6 +121,24 @@ export class ComposioError extends Error {
121 });
122 }
123 }
124 +
125 + /**
126 + * Helper method to combine stack traces when wrapping errors
127 + * This ensures the full call chain is preserved
128 + * @param originalStack The stack of the error being wrapped
129 + * @param currentStack The stack of the wrapper error
130 + * @returns Combined stack trace
131 + * @private
132 + */
133 + private static combineStackTraces(originalStack?: string, currentStack?: string): string | undefined {
134 + if (!originalStack) return currentStack;
135 + if (!currentStack) return originalStack;
136 +
137 + const currentHeader = currentStack.split('\n')[0];
138 + const originalStackBody = originalStack.split('\n').slice(1).join('\n');
139 +
140 + return `${currentHeader}\n${currentStack.split('\n').slice(1).join('\n')}\n\nCaused by:\n${originalStack}`;
141 + }
142
143 /**
144 * Extract and normalize error data for formatting
@@ -166,7 +189,12 @@ export class ComposioError extends Error {
189
190 // Add stack trace if requested
191 if (includeStack && stack) {
169 - data.stack = stack.split('\n').slice(1);
192 + if (stack.includes('Caused by:')) {
193 + const [currentStack, causeStack] = stack.split('Caused by:');
194 + data.stack = [...currentStack.split('\n').slice(1), 'Caused by:', ...causeStack.split('\n')];
195 + } else {
196 + data.stack = stack.split('\n').slice(1);
197 + }
198 }
199
200 return data;
packages/core/src/errors/ToolErrors.ts
+5 -5
@@ -91,11 +91,11 @@ export class ComposioToolExecutionError extends ComposioError {
91 ],
92 });
93
94 - this.error =
95 - originalError ||
96 - (options.cause instanceof Error
97 - ? (options.cause as Error)
98 - : new Error(String(options.cause)));
94 + this.error =
95 + originalError ||
96 + (options.cause instanceof Error ? options.cause :
97 + (options.cause ? new Error(String(options.cause)) : new Error('Unknown error')));
98 +
99 this.name = 'ComposioToolExecutionError';
100 }
101 }
packages/core/src/errors/ValidationErrors.ts
+1 -3
@@ -43,12 +43,10 @@ export class ValidationError extends ComposioError {
43
44 this.name = 'ValidationError';
45
46 - // Capture the original stack trace from where the error occurred
47 - // Error.captureStackTrace(this, this.constructor);
48 -
46 // Create a friendly error message for users
47 const userFriendlyMessage = this.generateUserFriendlyMessage();
48 this.message = `${message}: ${userFriendlyMessage}`;
49 +
50 }
51
52 private generateUserFriendlyMessage(): string {
packages/core/src/telemetry/Telemetry.ts
+8 -10
@@ -115,14 +115,12 @@ export class TelemetryService {
115 try {
116 return await originalMethod.apply(instance, args);
117 } catch (error) {
118 - // inject error id to the error, this is to ensure we can track the error in logs
119 - if (error instanceof Error && !error.errorId) {
120 - // if there is error id, it means the error is already handled
121 - error.errorId = getRandomUUID();
122 - this.prepareAndSendErrorTelemetry(error, instrumentedClassName, name, args);
118 + if (error instanceof Error) {
119 + if (!error.errorId) {
120 + error.errorId = getRandomUUID();
121 + this.prepareAndSendErrorTelemetry(error, instrumentedClassName, name, args);
122 + }
123 }
124 - // @TODO: check if this will send the error telemetry to the server
125 - // rethrow the error to be handled by the caller
124 throw error;
125 }
126 };
@@ -167,7 +165,7 @@ export class TelemetryService {
165 error_id: error.errorId || '',
166 error_message: error.message,
167 original_error: error.cause || error,
170 - current_stack: error.stack?.split('\n') || [],
168 + current_stack: error.stack ? error.stack.split('\n') : [],
169 description: `Original Call : ${this.telemetryMetadata?.source}:${instrumentedClassName}.${name}(${JSON.stringify(args)})`,
170 };
171 this.sendErrorTelemetry(telemetryPayload);
@@ -177,7 +175,7 @@ export class TelemetryService {
175 error_id: error.errorId || '',
176 error_message: error.message,
177 original_error: error.cause || error,
180 - current_stack: error.stack?.split('\n') || [],
178 + current_stack: error.stack ? error.stack.split('\n') : [],
179 error_code: error.code,
180 possible_fix: error.possibleFixes?.join('\n'),
181 description: `Original Call : ${instrumentedClassName}.${name}(${JSON.stringify(args)})`,
@@ -189,7 +187,7 @@ export class TelemetryService {
187 error_id: error.errorId || '',
188 error_message: error instanceof Error ? error.name : 'Unknown error',
189 original_error: error,
192 - current_stack: error.stack?.split('\n') || [],
190 + current_stack: error.stack ? error.stack.split('\n') : [],
191 description: `Original Call : ${this.telemetryMetadata?.source}:${instrumentedClassName}.${name}(${JSON.stringify(args)})`,
192 };
193 this.sendErrorTelemetry(telemetryPayload);