{"record":{"id":"c5065bea97d05e80","repo":"nestjs/nest","slug":"the-instancedecorator-function-threw-an-error-wh","errorCode":null,"errorMessage":"The \"instanceDecorator\" function threw an error while decorating an instance (${(err as Error)?.message ?? err}). The undecorated instance will be used instead.","messagePattern":"The \"instanceDecorator\" function threw an error while decorating an instance \\((.+?)\\)\\. The undecorated instance will be used instead\\.","errorType":"console","errorClass":null,"httpStatus":null,"severity":"warning","filePath":"packages/core/helpers/safe-instance-decorator.ts","lineNumber":21,"sourceCode":"type InstanceDecorator = (target: unknown) => unknown;\n\nconst logger = new Logger('InstrumentLogger');\n\n/**\n * Wraps an `instrument.instanceDecorator` so that a decorator throwing on a\n * given instance (e.g. when inspecting a Proxy whose traps throw outside of\n * their intended context, such as `nestjs-cls` proxy providers) does not\n * crash the application bootstrap. The original, undecorated instance is\n * used instead and a warning is logged.\n */\nexport function makeSafeInstanceDecorator(\n  decorator: InstanceDecorator,\n): InstanceDecorator {\n  return (target: unknown) => {\n    try {\n      return decorator(target);\n    } catch (err) {\n      logger.warn(\n        `The \"instanceDecorator\" function threw an error while decorating an instance (${\n          (err as Error)?.message ?? err\n        }). The undecorated instance will be used instead.`,\n      );\n      return target;\n    }\n  };\n}\n","sourceCodeStart":3,"sourceCodeEnd":30,"githubUrl":"https://github.com/nestjs/nest/blob/3f8a0ce1832fb30053f55856088371b097bbf7e1/packages/core/helpers/safe-instance-decorator.ts#L3-L30","documentation":"This warning is emitted by NestJS's instrumentation layer when the user-configured `instrument.instanceDecorator` hook (set via `Instrument` in `NestFactory.create` options) throws while wrapping a resolved provider instance. The framework wraps the decorator with `makeSafeInstanceDecorator` so that a broken decorator never crashes bootstrap: it logs this warning and falls back to using the original, undecorated instance. It is a resilience message, not a fatal error — the app keeps running, but instrumentation (tracing/metrics patching) is silently missing for that instance.","triggerScenarios":"Passing a custom `instanceDecorator` in the `instrument` options of `NestFactory.create()` / microservice / standalone app creation, and that decorator throwing on a specific instance. Known concrete trigger: decorating Proxy-based providers (e.g. `nestjs-cls` proxy providers) whose traps throw when the decorator inspects or clones the proxy; also any decorator that accesses properties (e.g. `Object.keys`, spread, `instance.constructor`) on exotic objects that throw on property access.","commonSituations":"Upgrading NestJS to a version that added the instanceDecorator instrumentation hook while using OpenTelemetry or tracing wrappers that assume plain objects; using `nestjs-cls` with `proxyProviders` (the documented culprit in the code comment); decorators that call `JSON.stringify` or iterate over instances with getters that throw; partially-initialized instances decorated during eager instantiation.","solutions":["Inspect the underlying message in the parentheses (the original thrown error) — it names the real cause; fix that (e.g. guard against Proxy objects in your decorator).","If using nestjs-cls proxy providers, wrap your instanceDecorator body in a check that skips Proxy/exotic instances (e.g. try accessing a marker property inside its own try/catch, or duck-type on the design token) instead of patching them.","Make your instanceDecorator defensive: never spread/clone/`Object.keys` the target; only wrap it in a new Proxy or attach methods, and catch its own errors internally.","If you never configured instrumentation, this warning is harmless — the undecorated instance is used and behavior is unchanged; you can silence it via logger levels.","Check for version mismatch between @nestjs/core and your instrumentation/telemetry packages and align them."],"exampleFix":"// before (in main.ts)\nconst app = await NestFactory.create(AppModule, {\n  instrument: {\n    instanceDecorator: (instance) => {\n      const copy = { ...instance }; // throws on proxies w/ throwing traps\n      patchMethods(copy);\n      return copy;\n    },\n  },\n});\n\n// after\nconst app = await NestFactory.create(AppModule, {\n  instrument: {\n    instanceDecorator: (instance) => {\n      if (instance == null || (typeof instance !== 'object' && typeof instance !== 'function')) {\n        return instance;\n      }\n      try {\n        // only wrap, never clone/inspect\n        return new Proxy(instance, tracingHandler);\n      } catch {\n        return instance; // degrade gracefully yourself\n      }\n    },\n  },\n});","handlingStrategy":"try-catch","validationCode":"// Before assigning the hook, smoke-test it on benign and hostile targets:\nconst decorator = (i: unknown) => { /* your impl */ };\nfor (const probe of [{}, () => {}, new Proxy({}, { get() { throw new Error('trap'); } })]) {\n  try { decorator(probe); } catch (e) {\n    console.warn('instanceDecorator unsafe on', probe, e);\n  }\n}\nconst app = await NestFactory.create(AppModule, {\n  instrument: { instanceDecorator: makeDefensive(decorator) },\n});","typeGuard":"function isPlainDecoratable(target: unknown): boolean {\n  if (target === null || (typeof target !== 'object' && typeof target !== 'function')) return false;\n  try {\n    // probes that typically throw on exotic proxies\n    Object.getPrototypeOf(target);\n    return true;\n  } catch {\n    return false;\n  }\n}","tryCatchPattern":"// Wrap your own decorator so IT never throws; Nest only warns-and-falls-back\nconst safeDecorator = (instance: unknown) => {\n  try {\n    return myInstrumentDecorator(instance);\n  } catch (err) {\n    myLogger.warn(`skipping instrumentation for instance: ${err}`);\n    return instance; // must return the original target\n  }\n};","preventionTips":["Never clone, spread, or Object.keys the instance inside instanceDecorator — only wrap it","Skip Proxy-based providers (nestjs-cls proxyProviders) explicitly before patching","Always return the original target from your decorator's failure path so the safe wrapper is a no-op","Smoke-test the decorator against {}, functions, and throwing Proxies before shipping","Run a canary bootstrap in CI with instrumentation enabled to catch decorator crashes before deploy"],"tags":["nestjs","instrumentation","decorator","proxy","bootstrap","nestjs-cls"],"backgroundTag":"custom-decorator-threw-during-instrumentation","analyzedSha":"3f8a0ce1832fb30053f55856088371b097bbf7e1","analyzedAt":"2026-08-27T05:19:01.476Z","contentChangedAt":"2026-08-27T05:19:01.476Z","schemaVersion":2},"datasetVersion":"2026-09-14T05:17:10.506Z"}