Skip to content

Commit

Permalink
perf(common): Improve error handling for undefined tokens
Browse files Browse the repository at this point in the history
In response to issue #12914, this commit enhances the Nest.js injector for better debugging efficiency. The improvement involves throwing a specific error when a token is undefined, aiding developers in quicker problem identification and resolution. The error message provides guidance on potential circular dependencies and references for further assistance.

Closes #12914
  • Loading branch information
mostafa8026 committed Jan 16, 2024
1 parent 4195e55 commit f242efa
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
6 changes: 6 additions & 0 deletions packages/common/decorators/core/inject.decorator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,12 @@ export function Inject<T = any>(
return (target: object, key: string | symbol | undefined, index?: number) => {
const type = token || Reflect.getMetadata('design:type', target, key);

if (!type) {
throw new Error(`Token is undefined at index: ${index}. This often occurs due to circular dependencies.
Ensure there are no circular dependencies in your files or barrel files.
For more details, refer to https://trilon.io/blog/avoiding-circular-dependencies-in-nestjs.`);
}

if (!isUndefined(index)) {
let dependencies =
Reflect.getMetadata(SELF_DECLARED_DEPS_METADATA, target) || [];
Expand Down
10 changes: 10 additions & 0 deletions packages/common/test/decorators/inject.decorator.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,14 @@ describe('@Inject', () => {
];
expect(metadata).to.be.eql(expectedMetadata);
});

it('should throw an error when token is undefined', () => {
const defineInvalidClass = () => {
class Test {
constructor(@Inject(undefined) invalidParam) {}
}
};

expect(defineInvalidClass).to.throw(/^Token is undefined/);
});
});

0 comments on commit f242efa

Please sign in to comment.