{"record":{"id":"5b92d0f873265c55","repo":"mastra-ai/mastra","slug":"error-message-schema-validation-error-cause-fie","errorCode":null,"errorMessage":"error.message (schema validation error, cause: field/errors)","messagePattern":"error\\.message \\(schema validation error, cause: field/errors\\)","errorType":"http","errorClass":"HTTPException","httpStatus":400,"severity":"error","filePath":"packages/server/src/server/handlers/datasets.ts","lineNumber":1216,"sourceCode":"          externalId?: string | null;\n          input: unknown;\n          groundTruth?: unknown;\n          expectedTrajectory?: unknown;\n          toolMocks?: DatasetItemToolMock[];\n          unmockedToolPolicy?: 'allow' | 'deny';\n          scorerIds?: string[];\n          metadata?: Record<string, unknown>;\n          source?: DatasetItemSource;\n        }>;\n      };\n      const ds = await mastra.datasets.get({ id: datasetId });\n      const addedItems = await ds.addItems({\n        items: items.map(item => ({ ...item, externalId: item.externalId ?? undefined })),\n      });\n      return { items: addedItems, count: addedItems.length };\n    } catch (error) {\n      if (isSchemaValidationError(error)) {\n        throw new HTTPException(400, {\n          message: error.message,\n          cause: { field: error.field, errors: error.errors },\n        });\n      }\n      if (error instanceof MastraError) {\n        if (error.id === 'DATASET_ITEM_IDENTITY_CONFLICT') {\n          throw new HTTPException(409, {\n            message: error.message,\n            cause: { conflicts: 'conflicts' in error ? error.conflicts : [] },\n          });\n        }\n        if (error.id === 'DATASET_ITEM_EXTERNAL_ID_INVALID') {\n          throw new HTTPException(400, { message: error.message, cause: { field: 'externalId' } });\n        }\n        throw new HTTPException(getHttpStatusForMastraError(error.id) as StatusCode, { message: error.message });\n      }\n      return handleError(error, 'Error batch inserting items');\n    }","sourceCodeStart":1198,"sourceCodeEnd":1234,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/packages/server/src/server/handlers/datasets.ts#L1198-L1234","documentation":"The BATCH_INSERT_ITEMS route (POST /datasets/:datasetId/items/batch) validates each item's input/groundTruth/etc. against the dataset's configured Zod schemas. When ds.addItems rejects with a schema validation error, the handler converts it to HTTP 400 with cause: { field, errors } detailing which field failed and why.","triggerScenarios":"POST /datasets/:datasetId/items/batch where one or more items' payload fields (input, groundTruth, expectedTrajectory, metadata) fail the dataset's schema — wrong types, missing required properties, or extra constraints violated.","commonSituations":"Client sends stringified JSON instead of a parsed object for input; dataset schema changed (new required field) while the client still posts the old shape; AI-generated items not conforming to schema; groundTruth provided when the dataset defines no groundTruth schema.","solutions":["Read cause.field and cause.errors in the 400 response to see exactly which item field failed validation.","Fetch the dataset details (GET /datasets/:datasetId) to inspect its input/groundTruth schemas and conform your items.","Validate items client-side with the same Zod schemas before calling the batch endpoint.","If the schema intentionally changed, update the producing code or regenerate the items."],"exampleFix":"// before\nawait client.batchInsertItems(dsId, [{ input: '{\"query\":\"hi\"}' }]); // 400 schema validation\n// after\nconst parsed = datasetInputSchema.parse(JSON.parse('{\"query\":\"hi\"}'));\nawait client.batchInsertItems(dsId, [{ input: parsed }]);","handlingStrategy":"validation","validationCode":"import { z } from 'zod';\nconst inputSchema = dataset.inputSchema; // same Zod schema the dataset was created with\nconst validated = items.map(item => ({\n  ...item,\n  input: inputSchema.parse(item.input),\n  ...(item.groundTruth && groundTruthSchema ? { groundTruth: groundTruthSchema.parse(item.groundTruth) } : {}),\n})); // throws ZodError with field details before the HTTP call","typeGuard":"function isSchemaValidationErrorBody(\n  body: unknown\n): body is { message: string; cause?: { field?: string; errors?: unknown } } {\n  return typeof body === 'object' && body !== null && 'message' in body;\n}","tryCatchPattern":"try {\n  const res = await fetch(`/api/datasets/${datasetId}/items/batch`, { method: 'POST', body: JSON.stringify({ items }) });\n  if (res.status === 400) {\n    const body = await res.json();\n    console.error(`Schema validation failed on field '${body.cause?.field}':`, body.cause?.errors);\n    return null;\n  }\n  if (!res.ok) throw new Error(await res.text());\n  return await res.json();\n} catch (err) {\n  console.error(err);\n  throw err;\n}","preventionTips":["Reuse the exact Zod schemas the dataset was created with for client-side validation before posting.","Parse JSON strings into objects before assigning to input/groundTruth.","Re-validate items after any dataset schema change (new required fields, changed types).","Surface cause.field and cause.errors from the 400 response in your tooling."],"tags":["http-400","schema-validation","zod","datasets","batch-insert"],"backgroundTag":"schema-validation-failed","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}