{"record":{"id":"fc5928e9cf09d940","repo":"toeverything/AFFiNE","slug":"validation-failed-error-n-message","errorCode":null,"errorMessage":"Validation Failed Error\\n${message}","messagePattern":"Validation Failed Error\\\\n(.+?)","errorType":"validation","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"packages/common/infra/src/orm/core/validators/index.ts","lineNumber":16,"sourceCode":"import { createEntityDataValidators, updateEntityDataValidators } from './data';\nimport { tableSchemaValidators } from './schema';\nimport { yjsDataValidators, yjsTableSchemaValidators } from './yjs';\n\ninterface ValidationError {\n  code: string;\n  error: Error;\n}\n\nfunction throwIfError(errors: ValidationError[]) {\n  if (errors.length) {\n    const message = errors\n      .map(({ code, error }) => `${code}: ${error.stack ?? error.message}`)\n      .join('\\n');\n\n    throw new Error('Validation Failed Error\\n' + message);\n  }\n}\n\nfunction validate<Validator extends { validate: (...args: any[]) => void }>(\n  rules: Record<string, Validator>,\n  ...payload: Parameters<Validator['validate']>\n) {\n  const errors: ValidationError[] = [];\n\n  for (const [code, validator] of Object.entries(rules)) {\n    try {\n      validator.validate(...payload);\n    } catch (e) {\n      errors.push({ code, error: e as Error });\n    }\n  }\n\n  throwIfError(errors);","sourceCodeStart":1,"sourceCodeEnd":34,"githubUrl":"https://github.com/toeverything/AFFiNE/blob/b4c8548c09da21b2898443559a5b846f0ccf5dd8/packages/common/infra/src/orm/core/validators/index.ts#L1-L34","documentation":"This is the aggregation wrapper used by the ORM's validate() helper: it runs every registered validator (each rule gets a code name like 'DataTypeShouldExactlyMatch' or 'PrimaryKeyShouldExist'), collects failures instead of stopping at the first, and throws one Error whose message lists 'code: stack' per failure under the 'Validation Failed Error' header. The real cause is always the first line after the header.","triggerScenarios":"Any table schema registration or data create/update that trips one or more of the underlying validators (errors 700–709). Multiple simultaneous violations produce multiple lines in one throw.","commonSituations":"First run after adding a new table with several schema mistakes (no PK, reserved field, bad optional config) — all reported at once; a bad insert that violates both type and required rules; tests that assert on validation behavior and need to parse the aggregated message.","solutions":["Read the first 'CODE: ...stack...' line under the header; fix that validator error (see errors 700–709 for each code).","Fix issues top-to-bottom — each line is an independent validator failure.","If the stack is noisy, match on the code prefix (e.g. /^PrimaryKeyShouldExist:/) to identify which rule fired.","In tests, assert on the presence of the code substring rather than the full message."],"exampleFix":"// before (asserting exact message, brittle with aggregated stacks)\nexpect(() => create()).toThrow('Field is required');\n\n// after (assert on the validator code embedded in the aggregate)\nexpect(() => create()).toThrow(/DataTypeShouldExactlyMatch: /);","handlingStrategy":"try-catch","validationCode":"// Run your own pre-checks mirroring the validator codes before create/set:\n// PrimaryKeyShouldExist, OnlyOnePrimaryKey, PrimaryKeyShouldNotBeOptional,\n// DataTypeShouldExactlyMatch (see errors 700-709)","typeGuard":null,"tryCatchPattern":"function parseValidation(e: unknown): { code: string; message: string }[] {\n  if (!(e instanceof Error) || !e.message.startsWith('Validation Failed Error')) return [];\n  return e.message\n    .split('\\n')\n    .slice(1)\n    .map(line => { const i = line.indexOf(':'); return { code: line.slice(0, i), message: line.slice(i + 2) }; });\n}\ntry { await db.doc.create(row); } catch (e) {\n  for (const v of parseValidation(e)) console.error(v.code, v.message);\n}","preventionTips":["In tests, assert on validator code substrings, not full messages","Treat the first line under the header as root cause","Register table definitions in unit tests so schema-level codes never reach production"],"tags":["orm","validation","aggregated-error","affine"],"backgroundTag":"schema-validation-failed","analyzedSha":"b4c8548c09da21b2898443559a5b846f0ccf5dd8","analyzedAt":"2026-08-18T21:16:52.546Z","contentChangedAt":"2026-08-18T21:16:52.546Z","schemaVersion":2},"datasetVersion":"2026-09-14T00:17:10.932Z"}