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

Improve error messages #37

Open
wants to merge 20 commits into
base: main
Choose a base branch
from
Open
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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
node_modules
lib
coverage
.idea
.DS_Store
88 changes: 88 additions & 0 deletions packages/brandi/spec/binding-error.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import { Container, injected, token } from '../src';

describe('common container error', () => {
const INITIAL_ERR_MSG = 'error to stop logger module from being created'

it('provides clear error when modules are functions', () => {
const createLoggerModule = () => {
throw new Error(INITIAL_ERR_MSG)
return {
log: (message: string) => {
// eslint-disable-next-line no-console
console.log(message)
},
}
}
type Logger = ReturnType<typeof createLoggerModule>

const createAdderModule = (logger: Logger) => {
return {
add: (a: number, b: number) => {
logger.log('adding')
return a + b
},
}
}
type Adder = ReturnType<typeof createAdderModule>

const TOKENS = {
logger: token<Logger>('logger'),
adder: token<Adder>('adder'),
}

const container = new Container()
injected(createAdderModule, TOKENS.logger)
container.bind(TOKENS.adder).toInstance(createAdderModule).inSingletonScope()
container.bind(TOKENS.logger).toInstance(createLoggerModule).inSingletonScope()

expect(() => {
container.get(TOKENS.adder)
}).toThrow(new Error(`Failed to get token 'adder':
0. Failed to resolve the binding for 'adder' token.
1. Failed to resolve the binding for 'logger' token.
2. Failed to instantiate createLoggerModule: ${INITIAL_ERR_MSG}`))
})

it('provides clear error when modules are classes', () => {
class LoggerModule {
constructor() {
throw new Error(INITIAL_ERR_MSG)
}
// eslint-disable-next-line
public log(message: string) {
// eslint-disable-next-line no-console
console.log(message);
}
}

class AdderModule {
constructor(
public loggerModule: LoggerModule,
) {
throw new Error('error to stop logger module from being created')
}
// eslint-disable-next-line
public add(a: number, b: number) {
this.loggerModule.log('adding')
return a + b
}
}

const TOKENS = {
logger: token<LoggerModule>('logger'),
adder: token<AdderModule>('adder'),
}

const container = new Container()
injected(AdderModule, TOKENS.logger)
container.bind(TOKENS.adder).toInstance(AdderModule).inSingletonScope()
container.bind(TOKENS.logger).toInstance(LoggerModule).inSingletonScope()

expect(() => {
container.get(TOKENS.adder)
}).toThrow(new Error(`Failed to get token 'adder':
0. Failed to resolve the binding for 'adder' token.
1. Failed to resolve the binding for 'logger' token.
2. Failed to instantiate LoggerModule: ${INITIAL_ERR_MSG}`))
})
})
36 changes: 25 additions & 11 deletions packages/brandi/src/container/Container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
isInstanceResolutionScopedBinding,
isInstanceSingletonScopedBinding,
} from './bindings';
import { failedToGetTokenErrorMessage, isClass } from "../lib";
import { BindingsVault } from './BindingsVault';
import { DependencyModule } from './DependencyModule';
import { ResolutionCache } from './ResolutionCache';
Expand Down Expand Up @@ -109,7 +110,11 @@ export class Container extends DependencyModule {
token: T,
conditions?: ResolutionCondition[],
): TokenType<T> {
return this.resolveToken(token, conditions) as TokenType<T>;
try {
return this.resolveToken(token, conditions) as TokenType<T>;
} catch(e) {
throw new Error(`Failed to get token '${token.__d}':\n${failedToGetTokenErrorMessage(e as Error)}`)
}
}

private resolveTokens(
Expand All @@ -131,7 +136,13 @@ export class Container extends DependencyModule {
): unknown {
const binding = this.vault.get(token, cache, conditions, target);

if (binding) return this.resolveBinding(binding, cache);
if (binding) {
try {
return this.resolveBinding(binding, cache);
} catch (e) {
throw new Error(`Failed to resolve the binding for '${token.__d}' token.`, { cause: e })
}
}
if (token.__o) return undefined;

throw new Error(`No matching bindings found for '${token.__d}' token.`);
Expand Down Expand Up @@ -231,16 +242,19 @@ export class Container extends DependencyModule {
}

try {
// @ts-expect-error: This expression is not callable.
const instance = creator(...parameters);
callableRegistry.set(creator, true);
return instance;
} catch {
// @ts-expect-error: This expression is not constructable.
// eslint-disable-next-line new-cap
const instance = new creator(...parameters);
callableRegistry.set(creator, false);
const creatorIsClass = isClass(creator)
const instance = creatorIsClass
? // @ts-expect-error: This expression is not constructable.
// eslint-disable-next-line new-cap
new creator(...parameters)
// @ts-expect-error: This expression is not callable.
: creator(...parameters);
callableRegistry.set(creator, !creatorIsClass);
return instance;
} catch (e) {
const error = e as Error
error.message = `Failed to instantiate ${creator.name}: ${error.message}`
throw error
}
}

Expand Down
13 changes: 13 additions & 0 deletions packages/brandi/src/lib.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
export function isClass(v: any) {
return typeof v === 'function' && /^\s*class\s+/.test(v.toString());
}

export function failedToGetTokenErrorMessage(e: Error) {
let error = e
const causes: Error[] = []
while (error) {
causes.push(error)
error = error.cause as Error
}
return causes.map((c, idx) => `${idx}. ${c.message}`).join('\n')
}