X Tutup
Skip to content

Commit 0319417

Browse files
committed
feat(Binding): improve errors
fix #4358 Closes #4360
1 parent 5bf6a3a commit 0319417

File tree

3 files changed

+46
-3
lines changed

3 files changed

+46
-3
lines changed

modules/angular2/src/core/di/binding.ts

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ import {
66
CONST_EXPR,
77
stringify,
88
isArray,
9+
isType,
10+
isFunction,
911
normalizeBool
1012
} from 'angular2/src/core/facade/lang';
1113
import {BaseException, WrappedException} from 'angular2/src/core/facade/exceptions';
@@ -344,7 +346,13 @@ export class BindingBuilder {
344346
* expect(injectorAlias.get(Vehicle) instanceof Car).toBe(true);
345347
* ```
346348
*/
347-
toClass(type: Type): Binding { return new Binding(this.token, {toClass: type}); }
349+
toClass(type: Type): Binding {
350+
if (!isType(type)) {
351+
throw new BaseException(
352+
`Trying to create a class binding but "${stringify(type)}" is not a class!`);
353+
}
354+
return new Binding(this.token, {toClass: type});
355+
}
348356

349357
/**
350358
* Binds a DI token to a value.
@@ -416,8 +424,12 @@ export class BindingBuilder {
416424
* expect(injector.get(String)).toEqual('Value: 3');
417425
* ```
418426
*/
419-
toFactory(factoryFunction: Function, dependencies?: any[]): Binding {
420-
return new Binding(this.token, {toFactory: factoryFunction, deps: dependencies});
427+
toFactory(factory: Function, dependencies?: any[]): Binding {
428+
if (!isFunction(factory)) {
429+
throw new BaseException(
430+
`Trying to create a factory binding but "${stringify(factory)}" is not a function!`);
431+
}
432+
return new Binding(this.token, {toFactory: factory, deps: dependencies});
421433
}
422434
}
423435

File renamed without changes.
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import {
2+
AsyncTestCompleter,
3+
beforeEach,
4+
ddescribe,
5+
describe,
6+
expect,
7+
iit,
8+
inject,
9+
it,
10+
xit,
11+
} from 'angular2/test_lib';
12+
13+
import {bind} from 'angular2/core';
14+
15+
export function main() {
16+
describe('binding', () => {
17+
18+
describe('type errors', () => {
19+
20+
it('should throw when trying to create a class binding and not passing a class', () => {
21+
expect(() => { bind('foo').toClass(<any>0); })
22+
.toThrowError('Trying to create a class binding but "0" is not a class!');
23+
});
24+
25+
it('should throw when trying to create a factory binding and not passing a function', () => {
26+
expect(() => { bind('foo').toFactory(<any>0); })
27+
.toThrowError('Trying to create a factory binding but "0" is not a function!');
28+
});
29+
});
30+
});
31+
}

0 commit comments

Comments
 (0)
X Tutup