Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
Mirrored from https://github.com/Camo67/composio.git
Synced Nov 21, 04:45 UTC
| 1 | # Error Handling in Composio SDK |
| 2 | |
| 3 | Proper error handling is essential for building robust applications with the Composio SDK. This guide explains the error classes provided by the SDK and how to handle errors effectively. |
| 4 | |
| 5 | ## Error Hierarchy |
| 6 | |
| 7 | Composio SDK provides a structured error hierarchy: |
| 8 | |
| 9 | - `ComposioError`: The base error class for all Composio errors |
| 10 | - `AuthConfigErrors`: Errors related to authentication configurations |
| 11 | - `ConnectedAccountsError`: Errors related to connected accounts |
| 12 | - `ConnectionRequestError`: Errors related to connection requests |
| 13 | - `ToolErrors`: Errors related to tools and tool execution |
| 14 | - `ToolkitErrors`: Errors related to toolkits |
| 15 | - `ValidationError`: Errors related to input validation |
| 16 | |
| 17 | ## Common Error Types |
| 18 | |
| 19 | ### Validation Errors |
| 20 | |
| 21 | Validation errors occur when the input to a method doesn't match the expected schema: |
| 22 | |
| 23 | ```typescript |
| 24 | try { |
| 25 | await composio.tools.get('default', { |
| 26 | invalidParam: 'value', // This will cause a validation error |
| 27 | }); |
| 28 | } catch (error) { |
| 29 | if (error instanceof ValidationError) { |
| 30 | console.error('Validation error:', error.message); |
| 31 | console.error('Validation details:', error.validationError); |
| 32 | } |
| 33 | } |
| 34 | ``` |
| 35 | |
| 36 | ### Tool Execution Errors |
| 37 | |
| 38 | Errors that occur during tool execution: |
| 39 | |
| 40 | ```typescript |
| 41 | try { |
| 42 | const result = await composio.tools.execute('GITHUB_GET_REPO', { |
| 43 | userId: 'default', |
| 44 | arguments: { |
| 45 | owner: 'composio', |
| 46 | // Missing 'repo' parameter will cause an error |
| 47 | }, |
| 48 | }); |
| 49 | } catch (error) { |
| 50 | if (error instanceof ComposioToolExecutionError) { |
| 51 | // The message names the tool and ends with the API's own message, when it sent one |
| 52 | console.error('Tool execution error:', error.message); |
| 53 | console.error('HTTP status:', error.statusCode); // e.g. 403, 410 |
| 54 | console.error('API error code:', error.apiErrorCode); |
| 55 | console.error('Request id:', error.requestId); |
| 56 | console.error('Try:', error.possibleFixes); |
| 57 | console.error('Client error:', error.cause); |
| 58 | } |
| 59 | } |
| 60 | ``` |
| 61 | |
| 62 | The same server details are available when the SDK fetches a tool, executes one through a session or the Tool Router, or hits a rate limit: `statusCode`, `requestId`, `apiErrorCode`, and `possibleFixes` come from the API response. A tool-fetch error keeps the client error as `cause`, like an execution error. |
| 63 | |
| 64 | ### Not Found Errors |
| 65 | |
| 66 | Errors that occur when a resource is not found: |
| 67 | |
| 68 | ```typescript |
| 69 | try { |
| 70 | await composio.tools.get('default', 'NON_EXISTENT_TOOL'); |
| 71 | } catch (error) { |
| 72 | if (error instanceof ComposioToolNotFoundError) { |
| 73 | console.error('Tool not found:', error.message); |
| 74 | console.error('HTTP status:', error.statusCode); |
| 75 | console.error('API error code:', error.apiErrorCode); |
| 76 | console.error('Try:', error.possibleFixes); |
| 77 | } |
| 78 | } |
| 79 | ``` |
| 80 | |
| 81 | ## Handling Errors in Tool Execution |
| 82 | |
| 83 | When executing tools, you should handle both SDK errors and execution result errors: |
| 84 | |
| 85 | ```typescript |
| 86 | try { |
| 87 | const result = await composio.tools.execute('GITHUB_GET_REPO', { |
| 88 | userId: 'default', |
| 89 | arguments: { |
| 90 | owner: 'composio', |
| 91 | repo: 'sdk', |
| 92 | }, |
| 93 | }); |
| 94 | |
| 95 | // Check if the execution was successful |
| 96 | if (result.successful) { |
| 97 | console.log('Repository details:', result.data); |
| 98 | } else { |
| 99 | // Handle unsuccessful execution |
| 100 | console.error('Execution failed:', result.error); |
| 101 | } |
| 102 | } catch (error) { |
| 103 | // Handle SDK errors |
| 104 | console.error('SDK error:', error.message); |
| 105 | } |
| 106 | ``` |
| 107 | |
| 108 | ## Error Handling with Connected Accounts |
| 109 | |
| 110 | Handle errors during the connection flow: |
| 111 | |
| 112 | ```typescript |
| 113 | try { |
| 114 | // Step 1: Authorize the toolkit |
| 115 | const connectionRequest = await composio.toolkits.authorize('user123', 'github'); |
| 116 | |
| 117 | // Step 2: Wait for the connection to be established |
| 118 | try { |
| 119 | const connectedAccount = await composio.connectedAccounts.waitForConnection( |
| 120 | connectionRequest.id, |
| 121 | 60000 // 60 second timeout |
| 122 | ); |
| 123 | console.log('Connected account:', connectedAccount); |
| 124 | } catch (timeoutError) { |
| 125 | if (timeoutError instanceof ConnectionRequestTimeoutError) { |
| 126 | console.error('Connection timed out. Please try again.'); |
| 127 | } else if (timeoutError instanceof ConnectionRequestFailedError) { |
| 128 | console.error('Connection failed:', timeoutError.message); |
| 129 | } |
| 130 | } |
| 131 | } catch (error) { |
| 132 | if (error instanceof ComposioAuthConfigNotFoundError) { |
| 133 | console.error('Auth config not found:', error.message); |
| 134 | } else { |
| 135 | console.error('Error initiating connection:', error.message); |
| 136 | } |
| 137 | } |
| 138 | ``` |
| 139 | |
| 140 | ## Global Error Handler |
| 141 | |
| 142 | For larger applications, consider implementing a global error handler: |
| 143 | |
| 144 | ```typescript |
| 145 | // Define a global error handler function |
| 146 | function handleComposioError(error: unknown): void { |
| 147 | if (error instanceof ValidationError) { |
| 148 | console.error('Validation error:', error.message); |
| 149 | } else if (error instanceof ComposioToolNotFoundError) { |
| 150 | console.error('Tool not found:', error.message); |
| 151 | } else if (error instanceof ComposioToolExecutionError) { |
| 152 | console.error('Tool execution error:', error.message); |
| 153 | } else if (error instanceof ComposioAuthConfigNotFoundError) { |
| 154 | console.error('Auth config not found:', error.message); |
| 155 | } else if (error instanceof ConnectionRequestFailedError) { |
| 156 | console.error('Connection failed:', error.message); |
| 157 | } else if (error instanceof ConnectionRequestTimeoutError) { |
| 158 | console.error('Connection timed out:', error.message); |
| 159 | } else if (error instanceof ComposioError) { |
| 160 | console.error('Composio error:', error.message); |
| 161 | } else { |
| 162 | console.error('Unexpected error:', error); |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | // Use the global error handler |
| 167 | try { |
| 168 | const result = await composio.tools.execute('GITHUB_GET_REPO', { |
| 169 | userId: 'default', |
| 170 | arguments: { |
| 171 | owner: 'composio', |
| 172 | repo: 'sdk', |
| 173 | }, |
| 174 | }); |
| 175 | |
| 176 | if (!result.successful) { |
| 177 | console.error('Execution failed:', result.error); |
| 178 | } |
| 179 | } catch (error) { |
| 180 | handleComposioError(error); |
| 181 | } |
| 182 | ``` |
| 183 | |
| 184 | ## Error Handling in Session Custom Tools |
| 185 | |
| 186 | When creating Tool Router custom tools, throw ordinary errors from the handler when execution cannot continue. The SDK wraps thrown errors into the standard session execution response. |
| 187 | |
| 188 | ```typescript |
| 189 | import { experimental_createTool } from '@composio/core'; |
| 190 | import { z } from 'zod'; |
| 191 | |
| 192 | const customTool = experimental_createTool('MY_CUSTOM_TOOL', { |
| 193 | name: 'My Custom Tool', |
| 194 | description: 'A custom tool with error handling', |
| 195 | inputParams: z.object({ |
| 196 | param1: z.string().describe('Required parameter'), |
| 197 | }), |
| 198 | execute: async (input) => { |
| 199 | const { param1 } = input; |
| 200 | if (param1.trim() === '') { |
| 201 | throw new Error('param1 cannot be empty'); |
| 202 | } |
| 203 | |
| 204 | const result = await someExternalService(param1); |
| 205 | return { result }; |
| 206 | }, |
| 207 | }); |
| 208 | ``` |
| 209 | |
| 210 | ## User-Friendly Error Display |
| 211 | |
| 212 | Composio SDK provides features to display errors in a more user-friendly way with colors and formatting: |
| 213 | |
| 214 | ### Using toString() |
| 215 | |
| 216 | The `toString()` method on `ComposioError` and its subclasses provides a formatted string representation of the error: |
| 217 | |
| 218 | ```typescript |
| 219 | try { |
| 220 | // Some operation that might fail |
| 221 | } catch (error) { |
| 222 | if (error instanceof ComposioError) { |
| 223 | // This will output a nicely formatted error message with color |
| 224 | console.error(error.toString()); |
| 225 | } |
| 226 | } |
| 227 | ``` |
| 228 | |
| 229 | ### Using prettyPrint() |
| 230 | |
| 231 | The `prettyPrint()` method provides an even more visually appealing error display: |
| 232 | |
| 233 | ```typescript |
| 234 | try { |
| 235 | // Some operation that might fail |
| 236 | } catch (error) { |
| 237 | if (error instanceof ComposioError) { |
| 238 | // This will print a beautifully formatted error with color directly to console.error |
| 239 | error.prettyPrint(); |
| 240 | |
| 241 | // You can include the stack trace by passing true |
| 242 | error.prettyPrint(true); |
| 243 | |
| 244 | // Important: Don't re-throw the error or log it again after pretty printing |
| 245 | // to avoid duplicate error messages |
| 246 | } |
| 247 | } |
| 248 | ``` |
| 249 | |
| 250 | > **Note:** When using `prettyPrint()`, avoid logging the error again or re-throwing it without handling, as this would result in duplicate error messages in the console. |
| 251 | |
| 252 | ### Using the handle Utility |
| 253 | |
| 254 | For a more consistent approach to error handling, use the static `handle` method: |
| 255 | |
| 256 | ```typescript |
| 257 | try { |
| 258 | // Some operation that might fail |
| 259 | } catch (error) { |
| 260 | // This handles all types of errors with proper formatting |
| 261 | ComposioError.handle(error); |
| 262 | |
| 263 | // Include stack trace |
| 264 | ComposioError.handle(error, { includeStack: true }); |
| 265 | } |
| 266 | ``` |
| 267 | |
| 268 | This method: |
| 269 | |
| 270 | - Automatically detects Composio errors and uses `prettyPrint` for them |
| 271 | - Formats standard errors with a similar style |
| 272 | - Handles unknown errors gracefully |
| 273 | |
| 274 | ### Using handleAndThrow for Fatal Errors |
| 275 | |
| 276 | For fatal errors that should stop execution, use the `handleAndThrow` method which displays the error and then throws it: |
| 277 | |
| 278 | ```typescript |
| 279 | try { |
| 280 | // Some operation that might fail |
| 281 | } catch (error) { |
| 282 | // Display the error and then throw it (for fatal errors) |
| 283 | ComposioError.handleAndThrow(error); |
| 284 | |
| 285 | // Include stack trace before throwing |
| 286 | ComposioError.handleAndThrow(error, true); |
| 287 | } |
| 288 | ``` |
| 289 | |
| 290 | This method: |
| 291 | |
| 292 | - Displays the error using the same formatting as `handle()` |
| 293 | - Always throws the error after displaying it |
| 294 | - Returns `never` type, indicating it always throws |
| 295 | - Is compatible with serverless environments (unlike `process.exit()`) |
| 296 | |
| 297 | ### Creating and Printing Errors |
| 298 | |
| 299 | You can use the static factory method to create and print errors in one step: |
| 300 | |
| 301 | ```typescript |
| 302 | // Create, print, and throw the error |
| 303 | throw ComposioError.createAndPrint('Something went wrong', { |
| 304 | code: 'CUSTOM_ERROR', |
| 305 | cause: 'The operation failed because of XYZ', |
| 306 | possibleFixes: ['Try solution A', 'Try solution B'], |
| 307 | }); |
| 308 | ``` |
| 309 | |
| 310 | This approach is particularly useful for creating custom error handlers or formatters. |
| 311 | |
| 312 | ## Best Practices |
| 313 | |
| 314 | 1. **Always use try/catch blocks** when calling SDK methods |
| 315 | 2. **Check result.successful** after tool execution |
| 316 | 3. **Provide specific error handling** for different error types |
| 317 | 4. **Log detailed error information** for debugging |
| 318 | 5. **Present user-friendly error messages** in your application |
| 319 | 6. **Set appropriate timeouts** for operations like waitForConnection |
| 320 | 7. **Validate inputs** before calling SDK methods |
| 321 | 8. **Implement retry logic** for transient errors |
| 322 | |
| 323 | ## Importing Error Classes |
| 324 | |
| 325 | All error classes are exported from the main SDK package, making them easy to import: |
| 326 | |
| 327 | ```typescript |
| 328 | import { |
| 329 | ComposioError, |
| 330 | ComposioNoAPIKeyError, |
| 331 | ComposioToolNotFoundError, |
| 332 | ValidationError, |
| 333 | } from '@composio/core'; |
| 334 | ``` |
| 335 | |
| 336 | You can also use the error handling utilities in your application: |
| 337 | |
| 338 | ```typescript |
| 339 | import { ComposioError } from '@composio/core'; |
| 340 | |
| 341 | // Centralized error handler |
| 342 | function handleApplicationError(error: unknown) { |
| 343 | // Use the built-in error handling utility |
| 344 | ComposioError.handle(error, { |
| 345 | includeStack: process.env.NODE_ENV === 'development', |
| 346 | }); |
| 347 | |
| 348 | // Add your custom application-specific error handling |
| 349 | // e.g., log to monitoring service, etc. |
| 350 | } |
| 351 | |
| 352 | // Use in try/catch blocks |
| 353 | try { |
| 354 | // Application code |
| 355 | } catch (error) { |
| 356 | handleApplicationError(error); |
| 357 | } |
| 358 | ``` |
| 359 | |
| 360 | If you want to create custom error types that extend the Composio error system: |
| 361 | |
| 362 | ```typescript |
| 363 | import { ComposioError } from '@composio/core'; |
| 364 | |
| 365 | class MyCustomError extends ComposioError { |
| 366 | constructor(message: string) { |
| 367 | super(message, { |
| 368 | code: 'MY_CUSTOM_ERROR', |
| 369 | possibleFixes: [ |
| 370 | 'Check your application configuration', |
| 371 | 'Ensure all required dependencies are installed', |
| 372 | ], |
| 373 | }); |
| 374 | this.name = 'MyCustomError'; |
| 375 | } |
| 376 | } |
| 377 | |
| 378 | // Use your custom error |
| 379 | try { |
| 380 | // Some condition |
| 381 | if (!config.isValid) { |
| 382 | throw new MyCustomError('Invalid configuration'); |
| 383 | } |
| 384 | } catch (error) { |
| 385 | ComposioError.handle(error); |
| 386 | } |
| 387 | ``` |