{"record":{"id":"ec9a42946b4f8bf5","repo":"apify/crawlee","slug":"statevalidationerror-this-persiststatekey-result","errorCode":null,"errorMessage":"StateValidationError(this.#persistStateKey, result.issues)","messagePattern":"StateValidationError\\(this\\.#persistStateKey, result\\.issues\\)","errorType":"validation","errorClass":"StateValidationError","httpStatus":null,"severity":"error","filePath":"packages/core/src/recoverable_state.ts","lineNumber":188,"sourceCode":"                this.#log.warning(`Failed to persist the state under key '${this.#persistStateKey}'.`, { error }),\n            );\n    }\n\n    /** Normalizes a conversion option into a function. Absent conversions pass the value through unchanged. */\n    #toConversion<TFrom, TTo>(conversion: StateConversion<TFrom, TTo> | undefined): (value: TFrom) => Promise<TTo> {\n        if (conversion === undefined) {\n            return async (value) => value as unknown as TTo;\n        }\n\n        if (typeof conversion === 'function') {\n            return async (value) => conversion(value);\n        }\n\n        return async (value) => {\n            const result = await conversion['~standard'].validate(value);\n\n            if (result.issues) {\n                throw new StateValidationError(this.#persistStateKey, result.issues);\n            }\n\n            return result.value;\n        };\n    }\n\n    /**\n     * Initialize the recoverable state.\n     *\n     * If persistence is enabled, this method loads the saved state and registers the object to listen for\n     * PERSIST_STATE events. A state established beforehand by {@apilink RecoverableState.reset} survives if there\n     * is no record to restore.\n     *\n     * Calling this again after a {@apilink RecoverableState.teardown} starts a new persistence window - the\n     * listener is registered again and the record reloaded.\n     *\n     * @returns The loaded state object\n     */","sourceCodeStart":170,"sourceCodeEnd":206,"githubUrl":"https://github.com/apify/crawlee/blob/dbe57fb09ca607ad59dcf998f3925ef9ac3bb26c/packages/core/src/recoverable_state.ts#L170-L206","documentation":"#toConversion wraps a schema into an async validator that runs '~standard'.validate and throws StateValidationError (keyed by the persistence key) when the value has validation issues. It is invoked from the RecoverableState constructor, so constructing a RecoverableState with a value that fails its schema throws immediately.","triggerScenarios":"new RecoverableState(...) where the initialValue (or value passed to the returned conversion) does not satisfy the provided schema.","commonSituations":"Passing a partially-built default state object that misses required fields; supplying the wrong schema for the value type; refactoring the state model without updating construction call sites.","solutions":["Read the validation issues attached to the error and fix the initial value accordingly","Validate defaults with the schema before constructing RecoverableState","Ensure the schema passed to the constructor matches the value's actual type","Add schema defaults for newly required fields so legacy callers still construct"],"exampleFix":"// before\nnew RecoverableState({ key: 'cart', schema: cartSchema, value: { items } });\n// after\nconst value = cartSchema.parse({ items, updatedAt: Date.now() });\nnew RecoverableState({ key: 'cart', schema: cartSchema, value });","handlingStrategy":"validation","validationCode":"const parsed = schema['~standard'].validate(initialValue);\nif ((await parsed).issues) console.warn('initialValue fails schema', (await parsed).issues);","typeGuard":"function isValidState(v): v is TState { return !schema['~standard'].validate(v).issues; }","tryCatchPattern":"try {\n  const rs = new RecoverableState({ key, schema, value });\n} catch (err) {\n  if (err instanceof StateValidationError) {\n    return new RecoverableState({ key, schema, value: schemaDefaults });\n  }\n  throw err;\n}","preventionTips":["Parse/validate default values with the same schema used by RecoverableState","Keep schema and state model definitions co-located so they change together","Add unit tests that construct RecoverableState with production defaults"],"tags":["validation","constructor","schema"],"backgroundTag":"schema-validation-failed","analyzedSha":"dbe57fb09ca607ad59dcf998f3925ef9ac3bb26c","analyzedAt":"2026-08-30T22:22:28.328Z","schemaVersion":2},"datasetVersion":"2026-08-30T23:17:21.991Z"}