Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf(common): Improve error handling for undefined tokens #13056

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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/);
});
});