forked from angular/angular
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reflective_exceptions.ts
286 lines (258 loc) · 8.17 KB
/
reflective_exceptions.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ListWrapper} from '../facade/collection';
import {BaseException, WrappedException} from '../facade/exceptions';
import {Type, isBlank, stringify} from '../facade/lang';
import {Provider} from './provider';
import {ReflectiveInjector} from './reflective_injector';
import {ReflectiveKey} from './reflective_key';
function findFirstClosedCycle(keys: any[]): any[] {
var res: any[] = [];
for (var i = 0; i < keys.length; ++i) {
if (ListWrapper.contains(res, keys[i])) {
res.push(keys[i]);
return res;
}
res.push(keys[i]);
}
return res;
}
function constructResolvingPath(keys: any[]): string {
if (keys.length > 1) {
var reversed = findFirstClosedCycle(ListWrapper.reversed(keys));
var tokenStrs = reversed.map(k => stringify(k.token));
return ' (' + tokenStrs.join(' -> ') + ')';
}
return '';
}
/**
* Base class for all errors arising from misconfigured providers.
* @stable
*/
export class AbstractProviderError extends BaseException {
/** @internal */
message: string;
/** @internal */
keys: ReflectiveKey[];
/** @internal */
injectors: ReflectiveInjector[];
/** @internal */
constructResolvingMessage: Function;
constructor(
injector: ReflectiveInjector, key: ReflectiveKey, constructResolvingMessage: Function) {
super('DI Exception');
this.keys = [key];
this.injectors = [injector];
this.constructResolvingMessage = constructResolvingMessage;
this.message = this.constructResolvingMessage(this.keys);
}
addKey(injector: ReflectiveInjector, key: ReflectiveKey): void {
this.injectors.push(injector);
this.keys.push(key);
this.message = this.constructResolvingMessage(this.keys);
}
get context() { return this.injectors[this.injectors.length - 1].debugContext(); }
}
/**
* Thrown when trying to retrieve a dependency by `Key` from {@link Injector}, but the
* {@link Injector} does not have a {@link Provider} for {@link Key}.
*
* ### Example ([live demo](http://plnkr.co/edit/vq8D3FRB9aGbnWJqtEPE?p=preview))
*
* ```typescript
* class A {
* constructor(b:B) {}
* }
*
* expect(() => Injector.resolveAndCreate([A])).toThrowError();
* ```
* @stable
*/
export class NoProviderError extends AbstractProviderError {
constructor(injector: ReflectiveInjector, key: ReflectiveKey) {
super(injector, key, function(keys: any[]) {
var first = stringify(ListWrapper.first(keys).token);
return `No provider for ${first}!${constructResolvingPath(keys)}`;
});
}
}
/**
* Thrown when dependencies form a cycle.
*
* ### Example ([live demo](http://plnkr.co/edit/wYQdNos0Tzql3ei1EV9j?p=info))
*
* ```typescript
* var injector = Injector.resolveAndCreate([
* {provide: "one", useFactory: (two) => "two", deps: [[new Inject("two")]]},
* {provide: "two", useFactory: (one) => "one", deps: [[new Inject("one")]]}
* ]);
*
* expect(() => injector.get("one")).toThrowError();
* ```
*
* Retrieving `A` or `B` throws a `CyclicDependencyError` as the graph above cannot be constructed.
* @stable
*/
export class CyclicDependencyError extends AbstractProviderError {
constructor(injector: ReflectiveInjector, key: ReflectiveKey) {
super(injector, key, function(keys: any[]) {
return `Cannot instantiate cyclic dependency!${constructResolvingPath(keys)}`;
});
}
}
/**
* Thrown when a constructing type returns with an Error.
*
* The `InstantiationError` class contains the original error plus the dependency graph which caused
* this object to be instantiated.
*
* ### Example ([live demo](http://plnkr.co/edit/7aWYdcqTQsP0eNqEdUAf?p=preview))
*
* ```typescript
* class A {
* constructor() {
* throw new Error('message');
* }
* }
*
* var injector = Injector.resolveAndCreate([A]);
* try {
* injector.get(A);
* } catch (e) {
* expect(e instanceof InstantiationError).toBe(true);
* expect(e.originalException.message).toEqual("message");
* expect(e.originalStack).toBeDefined();
* }
* ```
* @stable
*/
export class InstantiationError extends WrappedException {
/** @internal */
keys: ReflectiveKey[];
/** @internal */
injectors: ReflectiveInjector[];
constructor(
injector: ReflectiveInjector, originalException: any, originalStack: any,
key: ReflectiveKey) {
super('DI Exception', originalException, originalStack, null);
this.keys = [key];
this.injectors = [injector];
}
addKey(injector: ReflectiveInjector, key: ReflectiveKey): void {
this.injectors.push(injector);
this.keys.push(key);
}
get wrapperMessage(): string {
var first = stringify(ListWrapper.first(this.keys).token);
return `Error during instantiation of ${first}!${constructResolvingPath(this.keys)}.`;
}
get causeKey(): ReflectiveKey { return this.keys[0]; }
get context() { return this.injectors[this.injectors.length - 1].debugContext(); }
}
/**
* Thrown when an object other then {@link Provider} (or `Type`) is passed to {@link Injector}
* creation.
*
* ### Example ([live demo](http://plnkr.co/edit/YatCFbPAMCL0JSSQ4mvH?p=preview))
*
* ```typescript
* expect(() => Injector.resolveAndCreate(["not a type"])).toThrowError();
* ```
* @stable
*/
export class InvalidProviderError extends BaseException {
constructor(provider: any) {
super(`Invalid provider - only instances of Provider and Type are allowed, got: ${provider}`);
}
}
/**
* Thrown when the class has no annotation information.
*
* Lack of annotation information prevents the {@link Injector} from determining which dependencies
* need to be injected into the constructor.
*
* ### Example ([live demo](http://plnkr.co/edit/rHnZtlNS7vJOPQ6pcVkm?p=preview))
*
* ```typescript
* class A {
* constructor(b) {}
* }
*
* expect(() => Injector.resolveAndCreate([A])).toThrowError();
* ```
*
* This error is also thrown when the class not marked with {@link Injectable} has parameter types.
*
* ```typescript
* class B {}
*
* class A {
* constructor(b:B) {} // no information about the parameter types of A is available at runtime.
* }
*
* expect(() => Injector.resolveAndCreate([A,B])).toThrowError();
* ```
* @stable
*/
export class NoAnnotationError extends BaseException {
constructor(typeOrFunc: Type|Function, params: any[][]) {
super(NoAnnotationError._genMessage(typeOrFunc, params));
}
private static _genMessage(typeOrFunc: Type|Function, params: any[][]) {
var signature: string[] = [];
for (var i = 0, ii = params.length; i < ii; i++) {
var parameter = params[i];
if (isBlank(parameter) || parameter.length == 0) {
signature.push('?');
} else {
signature.push(parameter.map(stringify).join(' '));
}
}
return 'Cannot resolve all parameters for \'' + stringify(typeOrFunc) + '\'(' +
signature.join(', ') + '). ' +
'Make sure that all the parameters are decorated with Inject or have valid type annotations and that \'' +
stringify(typeOrFunc) + '\' is decorated with Injectable.';
}
}
/**
* Thrown when getting an object by index.
*
* ### Example ([live demo](http://plnkr.co/edit/bRs0SX2OTQiJzqvjgl8P?p=preview))
*
* ```typescript
* class A {}
*
* var injector = Injector.resolveAndCreate([A]);
*
* expect(() => injector.getAt(100)).toThrowError();
* ```
* @stable
*/
export class OutOfBoundsError extends BaseException {
constructor(index: number) { super(`Index ${index} is out-of-bounds.`); }
}
// TODO: add a working example after alpha38 is released
/**
* Thrown when a multi provider and a regular provider are bound to the same token.
*
* ### Example
*
* ```typescript
* expect(() => Injector.resolveAndCreate([
* new Provider("Strings", {useValue: "string1", multi: true}),
* new Provider("Strings", {useValue: "string2", multi: false})
* ])).toThrowError();
* ```
*/
export class MixingMultiProvidersWithRegularProvidersError extends BaseException {
constructor(provider1: any, provider2: any) {
super(
'Cannot mix multi providers and regular providers, got: ' + provider1.toString() + ' ' +
provider2.toString());
}
}