mastra-ai/mastra · error · HTTPException

error.message (MastraError rethrown with mapped status in LI

Error message

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

What it means

Fallback branch of the LIST_ITEM_VERSIONS route: when ds.getItemHistory (or mastra.datasets.get) throws a MastraError, the handler rethrows it as an HTTPException whose status code is derived from the Mastra error ID via getHttpStatusForMastraError, and whose message is the original error.message. The message you see is the underlying storage/dataset error surfaced over HTTP.

Source

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

  pathParamSchema: datasetAndItemIdPathParams,
  responseSchema: listItemVersionsResponseSchema,
  summary: 'Get item history',
  description: 'Returns the full SCD-2 history of the item across all dataset versions',
  tags: ['Datasets'],
  requiresAuth: true,
  handler: async ({ mastra, datasetId, itemId }) => {
    assertDatasetsAvailable();
    try {
      const ds = await mastra.datasets.get({ id: datasetId });
      const rows = await ds.getItemHistory({ itemId });
      // Check rows belong to this dataset
      if (rows.length > 0 && rows[0]?.datasetId !== datasetId) {
        throw new HTTPException(404, { message: `Item not found in dataset: ${itemId}` });
      }
      return { history: rows };
    } catch (error) {
      if (error instanceof MastraError) {
        throw new HTTPException(getHttpStatusForMastraError(error.id) as StatusCode, { message: error.message });
      }
      return handleError(error, 'Error listing item history');
    }
  },
});

export const GET_ITEM_VERSION_ROUTE = createRoute({
  method: 'GET',
  path: '/datasets/:datasetId/items/:itemId/versions/:datasetVersion',
  responseType: 'json',
  pathParamSchema: datasetItemVersionPathParams,
  responseSchema: datasetItemResponseSchema.nullable(),
  summary: 'Get item at specific dataset version',
  description: 'Returns the item as it existed at a specific dataset version',
  tags: ['Datasets'],
  requiresAuth: true,
  handler: async ({ mastra, datasetId, itemId, datasetVersion }) => {
    assertDatasetsAvailable();

View on GitHub (pinned to 75dd419e61)

Solutions

  1. Read error.message in the response — it names the underlying MastraError (and its ID region) to fix the root cause.
  2. Verify the datasetId exists: GET /api/datasets and confirm the ID.
  3. Check the storage backend configuration/connection (DATABASE_URL etc.) and that the storage adapter is healthy.
  4. Confirm the Mastra instance registers dataset storage (assertDatasetsAvailable passes) in the deployment being called.
Defensive patterns

Strategy: try-catch

Validate before calling

const datasets = await fetch('/api/datasets').then(r => r.json());
if (!datasets.datasets?.some(d => d.id === datasetId)) {
  throw new Error(`Dataset ${datasetId} does not exist on this server`);
}

Type guard

function isMastraErrorPayload(body: unknown): body is { message: string } {
  return typeof body === 'object' && body !== null && 'message' in body && typeof (body as any).message === 'string';
}

Try / catch

try {
  const res = await fetch(`/api/datasets/${datasetId}/items/${itemId}/history`);
  if (!res.ok) {
    const body = await res.json().catch(() => null);
    throw new Error(`history fetch failed (${res.status}): ${body?.message ?? res.statusText}`);
  }
  return await res.json();
} catch (err) {
  // storage/dataset MastraError: surface message, optionally retry transient storage failures
  console.error(err);
  throw err;
}

Prevention

When it happens

Trigger: GET /datasets/:datasetId/items/:itemId/history fails inside ds.getItemHistory or mastra.datasets.get with a MastraError (e.g. dataset not found, storage backend error, datasets feature unavailable).

Common situations: Dataset ID doesn't exist so storage throws; storage backend (LibSQL/PG/Upstash) unreachable or misconfigured; calling a deployments where the datasets feature/storage domain is not registered; serialization of storage failures into MastraError with mapped status codes.

Related errors


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