Skip to content

Commit b3f84f4

Browse files
authoredJan 23, 2024
Merge pull request #13056 from mostafa8026/perf/12914-readable-error-on-undefined-token
perf(common): Improve error handling for undefined tokens
2 parents 5bf5196 + f242efa commit b3f84f4

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed
 

‎packages/common/decorators/core/inject.decorator.ts

+6
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,12 @@ export function Inject<T = any>(
3939
return (target: object, key: string | symbol | undefined, index?: number) => {
4040
const type = token || Reflect.getMetadata('design:type', target, key);
4141

42+
if (!type) {
43+
throw new Error(`Token is undefined at index: ${index}. This often occurs due to circular dependencies.
44+
Ensure there are no circular dependencies in your files or barrel files.
45+
For more details, refer to https://trilon.io/blog/avoiding-circular-dependencies-in-nestjs.`);
46+
}
47+
4248
if (!isUndefined(index)) {
4349
let dependencies =
4450
Reflect.getMetadata(SELF_DECLARED_DEPS_METADATA, target) || [];

‎packages/common/test/decorators/inject.decorator.spec.ts

+10
Original file line numberDiff line numberDiff line change
@@ -22,4 +22,14 @@ describe('@Inject', () => {
2222
];
2323
expect(metadata).to.be.eql(expectedMetadata);
2424
});
25+
26+
it('should throw an error when token is undefined', () => {
27+
const defineInvalidClass = () => {
28+
class Test {
29+
constructor(@Inject(undefined) invalidParam) {}
30+
}
31+
};
32+
33+
expect(defineInvalidClass).to.throw(/^Token is undefined/);
34+
});
2535
});

0 commit comments

Comments
 (0)
Please sign in to comment.