Skip to content

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

Devin AI9ae791ab9c76
diff --git a/examples/error-handling-demo/src/index.ts b/examples/error-handling-demo/src/index.ts
new file mode 100644
index 000000000..9c2d4de09
--- /dev/null
+++ b/examples/error-handling-demo/src/index.ts
@@ -0,0 +1,52 @@
+import { Composio } from '@composio/core';
+import { ComposioError } from '@composio/core';
+
+async function level3() {
+ throw new ComposioError('Level 3 error', {
+ code: 'LEVEL_3_ERROR',
+ cause: new Error('Original cause'),
+ });
+}
+
+async function level2() {
+ try {
+ await level3();
+ } catch (error) {
+ throw new ComposioError('Level 2 error', {
+ code: 'LEVEL_2_ERROR',
+ cause: error,
+ });
+ }
+}
+
+async function level1() {
+ try {
+ await level2();
+ } catch (error) {
+ throw new ComposioError('Level 1 error', {
+ code: 'LEVEL_1_ERROR',
+ cause: error,
+ });
+ }
+}
+
+async function main() {
+ try {
+ const composio = new Composio({
+ apiKey: 'test-api-key',
+ });
+
+ await level1();
+ } catch (error) {
+ if (error instanceof ComposioError) {
+ error.prettyPrint(true);
+
+ console.log('\n\nRaw stack trace:');
+ console.log(error.stack);
+ } else {
+ console.error('Unexpected error:', error);
+ }
+ }
+}
+
+main().catch(console.error);
diff --git a/packages/core/src/errors/ComposioError.ts b/packages/core/src/errors/ComposioError.ts
index 5d3e84ed0..bafb8bf45 100644
--- a/packages/core/src/errors/ComposioError.ts
+++ b/packages/core/src/errors/ComposioError.ts
@@ -76,6 +76,11 @@ export class ComposioError extends Error {
constructor(message: string, options: ComposioErrorOptions = {}) {
super(message);
+ // Captures stack trace excluding the constructor frame first
+ if (Error.captureStackTrace) {
+ Error.captureStackTrace(this, this.constructor);
+ }
+
// Process the status code - either from options or from the cause if it's a BadRequestError
const statusCode =
options.statusCode ||
@@ -89,15 +94,15 @@ export class ComposioError extends Error {
// Node.js by default shows all the properties of the error object, so we are doing it conditionally
this.definePropertyIfExists('statusCode', statusCode);
this.definePropertyIfExists('cause', options.cause);
- this.definePropertyIfExists('stack', options.stack);
+
+ const combinedStack = options.cause instanceof Error
+ ? ComposioError.combineStackTraces(options.cause.stack, this.stack)
+ : options.stack || this.stack;
+ this.definePropertyIfExists('stack', combinedStack);
if (options.meta && Object.keys(options.meta).length > 0) {
this.definePropertyIfExists('meta', options.meta);
}
- // Captures stack trace excluding the constructor frame
- if (Error.captureStackTrace) {
- Error.captureStackTrace(this, this.constructor);
- }
}
/**
@@ -116,6 +121,24 @@ export class ComposioError extends Error {
});
}
}
+
+ /**
+ * Helper method to combine stack traces when wrapping errors
+ * This ensures the full call chain is preserved
+ * @param originalStack The stack of the error being wrapped
+ * @param currentStack The stack of the wrapper error
+ * @returns Combined stack trace
+ * @private
+ */
+ private static combineStackTraces(originalStack?: string, currentStack?: string): string | undefined {
+ if (!originalStack) return currentStack;
+ if (!currentStack) return originalStack;
+
+ const currentHeader = currentStack.split('\n')[0];
+ const originalStackBody = originalStack.split('\n').slice(1).join('\n');
+
+ return `${currentHeader}\n${currentStack.split('\n').slice(1).join('\n')}\n\nCaused by:\n${originalStack}`;
+ }
/**
* Extract and normalize error data for formatting
@@ -166,7 +189,12 @@ export class ComposioError extends Error {
// Add stack trace if requested
if (includeStack && stack) {
- data.stack = stack.split('\n').slice(1);
+ if (stack.includes('Caused by:')) {
+ const [currentStack, causeStack] = stack.split('Caused by:');
+ data.stack = [...currentStack.split('\n').slice(1), 'Caused by:', ...causeStack.split('\n')];
+ } else {
+ data.stack = stack.split('\n').slice(1);
+ }
}
return data;
diff --git a/packages/core/src/errors/ToolErrors.ts b/packages/core/src/errors/ToolErrors.ts
index b4097d8c1..e3ddddea1 100644
--- a/packages/core/src/errors/ToolErrors.ts
+++ b/packages/core/src/errors/ToolErrors.ts
@@ -91,11 +91,11 @@ export class ComposioToolExecutionError extends ComposioError {
],
});
- this.error =
- originalError ||
- (options.cause instanceof Error
- ? (options.cause as Error)
- : new Error(String(options.cause)));
+ this.error =
+ originalError ||
+ (options.cause instanceof Error ? options.cause :
+ (options.cause ? new Error(String(options.cause)) : new Error('Unknown error')));
+
this.name = 'ComposioToolExecutionError';
}
}
diff --git a/packages/core/src/errors/ValidationErrors.ts b/packages/core/src/errors/ValidationErrors.ts
index ca56a6b0d..dcab5f100 100644
--- a/packages/core/src/errors/ValidationErrors.ts
+++ b/packages/core/src/errors/ValidationErrors.ts
@@ -43,12 +43,10 @@ export class ValidationError extends ComposioError {
this.name = 'ValidationError';
- // Capture the original stack trace from where the error occurred
- // Error.captureStackTrace(this, this.constructor);
-
// Create a friendly error message for users
const userFriendlyMessage = this.generateUserFriendlyMessage();
this.message = `${message}: ${userFriendlyMessage}`;
+
}
private generateUserFriendlyMessage(): string {
diff --git a/packages/core/src/telemetry/Telemetry.ts b/packages/core/src/telemetry/Telemetry.ts
index 149e7ee7b..86d9cfdfc 100644
--- a/packages/core/src/telemetry/Telemetry.ts
+++ b/packages/core/src/telemetry/Telemetry.ts
@@ -115,14 +115,12 @@ export class TelemetryService {
try {
return await originalMethod.apply(instance, args);
} catch (error) {
- // inject error id to the error, this is to ensure we can track the error in logs
- if (error instanceof Error && !error.errorId) {
- // if there is error id, it means the error is already handled
- error.errorId = getRandomUUID();
- this.prepareAndSendErrorTelemetry(error, instrumentedClassName, name, args);
+ if (error instanceof Error) {
+ if (!error.errorId) {
+ error.errorId = getRandomUUID();
+ this.prepareAndSendErrorTelemetry(error, instrumentedClassName, name, args);
+ }
}
- // @TODO: check if this will send the error telemetry to the server
- // rethrow the error to be handled by the caller
throw error;
}
};
@@ -167,7 +165,7 @@ export class TelemetryService {
error_id: error.errorId || '',
error_message: error.message,
original_error: error.cause || error,
- current_stack: error.stack?.split('\n') || [],
+ current_stack: error.stack ? error.stack.split('\n') : [],
description: `Original Call : ${this.telemetryMetadata?.source}:${instrumentedClassName}.${name}(${JSON.stringify(args)})`,
};
this.sendErrorTelemetry(telemetryPayload);
@@ -177,7 +175,7 @@ export class TelemetryService {
error_id: error.errorId || '',
error_message: error.message,
original_error: error.cause || error,
- current_stack: error.stack?.split('\n') || [],
+ current_stack: error.stack ? error.stack.split('\n') : [],
error_code: error.code,
possible_fix: error.possibleFixes?.join('\n'),
description: `Original Call : ${instrumentedClassName}.${name}(${JSON.stringify(args)})`,
@@ -189,7 +187,7 @@ export class TelemetryService {
error_id: error.errorId || '',
error_message: error instanceof Error ? error.name : 'Unknown error',
original_error: error,
- current_stack: error.stack?.split('\n') || [],
+ current_stack: error.stack ? error.stack.split('\n') : [],
description: `Original Call : ${this.telemetryMetadata?.source}:${instrumentedClassName}.${name}(${JSON.stringify(args)})`,
};
this.sendErrorTelemetry(telemetryPayload);