mastra-ai/mastra · error · HTTPException

error.message (MastraError rethrown with mapped status in BA

Error message

error.message (MastraError rethrown with mapped status in BATCH_DELETE_ITEMS route)

What it means

Fallback branch of the BATCH_DELETE_ITEMS route (DELETE /datasets/:datasetId/items/batch): if ds.deleteItems throws a MastraError, the handler rethrows it as an HTTPException whose status is mapped from the error ID via getHttpStatusForMastraError and whose body carries the original error.message.

Source

Thrown at packages/server/src/server/handlers/datasets.ts:1258

  path: '/datasets/:datasetId/items/batch',
  responseType: 'json',
  pathParamSchema: datasetIdPathParams,
  bodySchema: batchDeleteItemsBodySchema,
  responseSchema: batchDeleteItemsResponseSchema,
  summary: 'Batch delete items from dataset',
  description: 'Deletes multiple items from the dataset in a single operation (single version entry)',
  tags: ['Datasets'],
  requiresAuth: true,
  handler: async ({ mastra, datasetId, ...params }) => {
    assertDatasetsAvailable();
    try {
      const { itemIds } = params as { itemIds: string[] };
      const ds = await mastra.datasets.get({ id: datasetId });
      await ds.deleteItems({ itemIds });
      return { success: true, deletedCount: itemIds.length };
    } catch (error) {
      if (error instanceof MastraError) {
        throw new HTTPException(getHttpStatusForMastraError(error.id) as StatusCode, { message: error.message });
      }
      return handleError(error, 'Error bulk deleting items');
    }
  },
});

// ============================================================================
// AI Generation
// ============================================================================

const GENERATE_ITEMS_SYSTEM_PROMPT = `You are a test data generation expert. Your job is to generate realistic, diverse test data items for an AI agent evaluation dataset.

You will be given context about the agent being tested — its purpose, system prompt, and available tools. Use this to generate inputs that thoroughly exercise the agent's capabilities.

Generate test items that:
1. Are realistic and diverse — cover edge cases, different complexities, and various scenarios
2. Match the provided schemas exactly
3. Include ground truth values when a ground truth schema is provided

View on GitHub (pinned to 75dd419e61)

Solutions

  1. Check the response status and error.message to identify the mapped MastraError.
  2. Verify the datasetId exists via GET /api/datasets.
  3. Confirm the itemIds list is non-empty and well-formed (array of strings) per batchDeleteItemsBodySchema.
  4. Check storage backend health; retry transient failures with backoff.
Defensive patterns

Strategy: try-catch

Validate before calling

if (!Array.isArray(itemIds) || itemIds.length === 0 || itemIds.some(id => typeof id !== 'string' || !id)) {
  throw new Error('itemIds must be a non-empty array of non-empty strings');
}
const datasets = await fetch('/api/datasets').then(r => r.json());
if (!datasets.datasets?.some(d => d.id === datasetId)) {
  throw new Error(`Dataset ${datasetId} not found before batch delete`);
}

Type guard

function isValidItemIds(v: unknown): v is string[] {
  return Array.isArray(v) && v.length > 0 && v.every(id => typeof id === 'string' && id.length > 0);
}

Try / catch

try {
  const res = await fetch(`/api/datasets/${datasetId}/items/batch`, {
    method: 'DELETE',
    body: JSON.stringify({ itemIds }),
  });
  if (!res.ok) {
    const body = await res.json().catch(() => null);
    throw new Error(`batch delete failed (${res.status}): ${body?.message ?? res.statusText}`);
  }
  return await res.json();
} catch (err) {
  if (isTransientStorageError(err)) {
    await sleep(backoff);
    return batchDeleteItems(datasetId, itemIds); // deletes are idempotent
  }
  throw err;
}

Prevention

When it happens

Trigger: DELETE /datasets/:datasetId/items/batch where mastra.datasets.get or ds.deleteItems throws a MastraError — nonexistent dataset, storage failure, or a delete constraint error raised by the storage adapter.

Common situations: Deleting items from a dataset ID that doesn't exist (typo or stale cache); storage backend outage; itemIds already deleted by a concurrent request if storage surfaces that as a MastraError; datasets feature not configured in the deployment.

Related errors


AI-assisted analysis of mastra-ai/mastra@75dd419e61 (2026-08-30). Data as JSON: /api/errors/c8937f74a0528b61. Report an issue: GitHub.