/sdk
/typescript
/error handling

Error Handling Guide

Throwing Errors

@Tool({ name: 'get_user' })
async getUser(input: any) {
  const user = await this.userService.findById(input.user_id);
  
  if (!user) {
    throw new Error('User not found');
  }
  
  return user;
}

Custom Errors

export class UserNotFoundError extends Error {
  constructor(userId: string) {
    super(\`User \${userId} not found\`);
    this.name = 'UserNotFoundError';
  }
}

@Tool({ name: 'get_user' })
async getUser(input: any) {
  const user = await this.userService.findById(input.user_id);
  
  if (!user) {
    throw new UserNotFoundError(input.user_id);
  }
  
  return user;
}

Exception Filters

@ExceptionFilter()
export class HttpExceptionFilter {
  catch(exception: any, context: ExecutionContext) {
    return {
      statusCode: exception.status || 500,
      message: exception.message,
      timestamp: new Date().toISOString()
    };
  }
}

@Tool({ name: 'risky_operation' })
@UseFilters(HttpExceptionFilter)
async riskyOperation(input: any) {
  // Errors handled by filter
}

Best Practices

  1. Be specific - Use custom error classes
  2. Log errors - Use context.logger.error()
  3. Don't swallow - Always re-throw or handle
  4. User-friendly messages - Don't expose internals
  5. Use filters - Centralized error handling

Next Steps