Skip to content

Commit

Permalink
Merge pull request #13056 from mostafa8026/perf/12914-readable-error-…
Browse files Browse the repository at this point in the history
…on-undefined-token

perf(common): Improve error handling for undefined tokens
  • Loading branch information
kamilmysliwiec authored Jan 23, 2024
2 parents 5bf5196 + f242efa commit b3f84f4
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 b3f84f4

Please sign in to comment.