diff --git a/modules/@angular/common/src/directives/ng_for.ts b/modules/@angular/common/src/directives/ng_for.ts index 80be308f29..691d30bf13 100644 --- a/modules/@angular/common/src/directives/ng_for.ts +++ b/modules/@angular/common/src/directives/ng_for.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException, ChangeDetectorRef, CollectionChangeRecord, DefaultIterableDiffer, Directive, DoCheck, EmbeddedViewRef, Input, IterableDiffer, IterableDiffers, OnChanges, SimpleChanges, TemplateRef, TrackByFn, ViewContainerRef} from '@angular/core'; +import {ChangeDetectorRef, CollectionChangeRecord, DefaultIterableDiffer, Directive, DoCheck, EmbeddedViewRef, Input, IterableDiffer, IterableDiffers, OnChanges, SimpleChanges, TemplateRef, TrackByFn, ViewContainerRef} from '@angular/core'; import {getTypeNameForDebugging, isBlank, isPresent} from '../facade/lang'; @@ -112,7 +112,7 @@ export class NgFor implements DoCheck, OnChanges { try { this._differ = this._iterableDiffers.find(value).create(this._cdr, this.ngForTrackBy); } catch (e) { - throw new BaseException( + throw new Error( `Cannot find a differ supporting object '${value}' of type '${getTypeNameForDebugging(value)}'. NgFor only supports binding to Iterables such as Arrays.`); } } diff --git a/modules/@angular/common/src/location/path_location_strategy.ts b/modules/@angular/common/src/location/path_location_strategy.ts index 54fbdbc2a8..4560eb111d 100644 --- a/modules/@angular/common/src/location/path_location_strategy.ts +++ b/modules/@angular/common/src/location/path_location_strategy.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException, Inject, Injectable, Optional} from '@angular/core'; +import {Inject, Injectable, Optional} from '@angular/core'; import {isBlank} from '../facade/lang'; @@ -53,7 +53,7 @@ export class PathLocationStrategy extends LocationStrategy { } if (isBlank(href)) { - throw new BaseException( + throw new Error( `No base href set. Please provide a value for the APP_BASE_HREF token or add a base element to the document.`); } diff --git a/modules/@angular/common/src/pipes/async_pipe.ts b/modules/@angular/common/src/pipes/async_pipe.ts index 2507794282..7598729f2a 100644 --- a/modules/@angular/common/src/pipes/async_pipe.ts +++ b/modules/@angular/common/src/pipes/async_pipe.ts @@ -9,7 +9,7 @@ import {ChangeDetectorRef, OnDestroy, Pipe, WrappedValue} from '@angular/core'; import {EventEmitter, Observable} from '../facade/async'; import {isBlank, isPresent, isPromise} from '../facade/lang'; -import {InvalidPipeArgumentException} from './invalid_pipe_argument_exception'; +import {InvalidPipeArgumentError} from './invalid_pipe_argument_error'; interface SubscriptionStrategy { createSubscription(async: any, updateLatestValue: any): any; @@ -128,7 +128,7 @@ export class AsyncPipe implements OnDestroy { } else if ((obj).subscribe) { return _observableStrategy; } else { - throw new InvalidPipeArgumentException(AsyncPipe, obj); + throw new InvalidPipeArgumentError(AsyncPipe, obj); } } diff --git a/modules/@angular/common/src/pipes/date_pipe.ts b/modules/@angular/common/src/pipes/date_pipe.ts index 6aa9195842..f2f9ffe41f 100644 --- a/modules/@angular/common/src/pipes/date_pipe.ts +++ b/modules/@angular/common/src/pipes/date_pipe.ts @@ -11,8 +11,7 @@ import {Inject, LOCALE_ID, Pipe, PipeTransform} from '@angular/core'; import {StringMapWrapper} from '../facade/collection'; import {DateFormatter} from '../facade/intl'; import {DateWrapper, NumberWrapper, isBlank, isDate, isString} from '../facade/lang'; - -import {InvalidPipeArgumentException} from './invalid_pipe_argument_exception'; +import {InvalidPipeArgumentError} from './invalid_pipe_argument_error'; /** @@ -102,7 +101,7 @@ export class DatePipe implements PipeTransform { if (isBlank(value)) return null; if (!this.supports(value)) { - throw new InvalidPipeArgumentException(DatePipe, value); + throw new InvalidPipeArgumentError(DatePipe, value); } if (NumberWrapper.isNumeric(value)) { diff --git a/modules/@angular/common/src/pipes/i18n_plural_pipe.ts b/modules/@angular/common/src/pipes/i18n_plural_pipe.ts index cd2064db5a..5f1d99443c 100644 --- a/modules/@angular/common/src/pipes/i18n_plural_pipe.ts +++ b/modules/@angular/common/src/pipes/i18n_plural_pipe.ts @@ -9,7 +9,7 @@ import {Pipe, PipeTransform} from '@angular/core'; import {StringWrapper, isBlank, isStringMap} from '../facade/lang'; import {NgLocalization, getPluralCategory} from '../localization'; -import {InvalidPipeArgumentException} from './invalid_pipe_argument_exception'; +import {InvalidPipeArgumentError} from './invalid_pipe_argument_error'; const _INTERPOLATION_REGEXP: RegExp = /#/g; @@ -58,7 +58,7 @@ export class I18nPluralPipe implements PipeTransform { if (isBlank(value)) return ''; if (!isStringMap(pluralMap)) { - throw new InvalidPipeArgumentException(I18nPluralPipe, pluralMap); + throw new InvalidPipeArgumentError(I18nPluralPipe, pluralMap); } const key = getPluralCategory(value, Object.keys(pluralMap), this._localization); diff --git a/modules/@angular/common/src/pipes/i18n_select_pipe.ts b/modules/@angular/common/src/pipes/i18n_select_pipe.ts index 3def3b1a81..deeaf4615e 100644 --- a/modules/@angular/common/src/pipes/i18n_select_pipe.ts +++ b/modules/@angular/common/src/pipes/i18n_select_pipe.ts @@ -8,7 +8,7 @@ import {Pipe, PipeTransform} from '@angular/core'; import {isBlank, isStringMap} from '../facade/lang'; -import {InvalidPipeArgumentException} from './invalid_pipe_argument_exception'; +import {InvalidPipeArgumentError} from './invalid_pipe_argument_error'; /** * @@ -47,7 +47,7 @@ export class I18nSelectPipe implements PipeTransform { if (isBlank(value)) return ''; if (!isStringMap(mapping)) { - throw new InvalidPipeArgumentException(I18nSelectPipe, mapping); + throw new InvalidPipeArgumentError(I18nSelectPipe, mapping); } return mapping.hasOwnProperty(value) ? mapping[value] : ''; diff --git a/modules/@angular/common/src/pipes/invalid_pipe_argument_error.ts b/modules/@angular/common/src/pipes/invalid_pipe_argument_error.ts index 42d9f6b9db..349a7fd07f 100644 --- a/modules/@angular/common/src/pipes/invalid_pipe_argument_error.ts +++ b/modules/@angular/common/src/pipes/invalid_pipe_argument_error.ts @@ -6,10 +6,12 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException, Type} from '@angular/core'; +import {Type} from '@angular/core'; + +import {BaseError} from '../facade/errors'; import {stringify} from '../facade/lang'; -export class InvalidPipeArgumentException extends BaseException { +export class InvalidPipeArgumentError extends BaseError { constructor(type: Type, value: Object) { super(`Invalid argument '${value}' for pipe '${stringify(type)}'`); } diff --git a/modules/@angular/common/src/pipes/lowercase_pipe.ts b/modules/@angular/common/src/pipes/lowercase_pipe.ts index d97ad0a276..e56452d5b0 100644 --- a/modules/@angular/common/src/pipes/lowercase_pipe.ts +++ b/modules/@angular/common/src/pipes/lowercase_pipe.ts @@ -8,7 +8,7 @@ import {Pipe, PipeTransform} from '@angular/core'; import {isBlank, isString} from '../facade/lang'; -import {InvalidPipeArgumentException} from './invalid_pipe_argument_exception'; +import {InvalidPipeArgumentError} from './invalid_pipe_argument_error'; /** @@ -25,7 +25,7 @@ export class LowerCasePipe implements PipeTransform { transform(value: string): string { if (isBlank(value)) return value; if (!isString(value)) { - throw new InvalidPipeArgumentException(LowerCasePipe, value); + throw new InvalidPipeArgumentError(LowerCasePipe, value); } return value.toLowerCase(); } diff --git a/modules/@angular/common/src/pipes/number_pipe.ts b/modules/@angular/common/src/pipes/number_pipe.ts index ae6ebca4c2..7027198ac4 100644 --- a/modules/@angular/common/src/pipes/number_pipe.ts +++ b/modules/@angular/common/src/pipes/number_pipe.ts @@ -11,7 +11,7 @@ import {Inject, LOCALE_ID, Pipe, PipeTransform, Type} from '@angular/core'; import {NumberFormatStyle, NumberFormatter} from '../facade/intl'; import {NumberWrapper, isBlank, isNumber, isPresent, isString} from '../facade/lang'; -import {InvalidPipeArgumentException} from './invalid_pipe_argument_exception'; +import {InvalidPipeArgumentError} from './invalid_pipe_argument_error'; const _NUMBER_FORMAT_REGEXP = /^(\d+)?\.((\d+)(\-(\d+))?)?$/; @@ -22,7 +22,7 @@ function formatNumber( // Convert strings to numbers value = isString(value) && NumberWrapper.isNumeric(value) ? +value : value; if (!isNumber(value)) { - throw new InvalidPipeArgumentException(pipe, value); + throw new InvalidPipeArgumentError(pipe, value); } let minInt: number; let minFraction: number; diff --git a/modules/@angular/common/src/pipes/slice_pipe.ts b/modules/@angular/common/src/pipes/slice_pipe.ts index 9bd856a28b..e1bde8030c 100644 --- a/modules/@angular/common/src/pipes/slice_pipe.ts +++ b/modules/@angular/common/src/pipes/slice_pipe.ts @@ -9,7 +9,7 @@ import {Pipe, PipeTransform} from '@angular/core'; import {ListWrapper} from '../facade/collection'; import {StringWrapper, isArray, isBlank, isString} from '../facade/lang'; -import {InvalidPipeArgumentException} from './invalid_pipe_argument_exception'; +import {InvalidPipeArgumentError} from './invalid_pipe_argument_error'; /** * Creates a new List or String containing only a subset (slice) of the @@ -72,7 +72,7 @@ export class SlicePipe implements PipeTransform { transform(value: any, start: number, end: number = null): any { if (isBlank(value)) return value; if (!this.supports(value)) { - throw new InvalidPipeArgumentException(SlicePipe, value); + throw new InvalidPipeArgumentError(SlicePipe, value); } if (isString(value)) { return StringWrapper.slice(value, start, end); diff --git a/modules/@angular/common/src/pipes/uppercase_pipe.ts b/modules/@angular/common/src/pipes/uppercase_pipe.ts index 2b948142d0..d4966c4612 100644 --- a/modules/@angular/common/src/pipes/uppercase_pipe.ts +++ b/modules/@angular/common/src/pipes/uppercase_pipe.ts @@ -8,7 +8,7 @@ import {Pipe, PipeTransform} from '@angular/core'; import {isBlank, isString} from '../facade/lang'; -import {InvalidPipeArgumentException} from './invalid_pipe_argument_exception'; +import {InvalidPipeArgumentError} from './invalid_pipe_argument_error'; /** * Implements uppercase transforms to text. @@ -24,7 +24,7 @@ export class UpperCasePipe implements PipeTransform { transform(value: string): string { if (isBlank(value)) return value; if (!isString(value)) { - throw new InvalidPipeArgumentException(UpperCasePipe, value); + throw new InvalidPipeArgumentError(UpperCasePipe, value); } return value.toUpperCase(); } diff --git a/modules/@angular/compiler/core_private.ts b/modules/@angular/compiler/core_private.ts index 82cd3c0576..b6e3b5de39 100644 --- a/modules/@angular/compiler/core_private.ts +++ b/modules/@angular/compiler/core_private.ts @@ -97,3 +97,7 @@ export var collectAndResolveStyles: typeof r.collectAndResolveStyles = r.collect export var renderStyles: typeof r.renderStyles = r.renderStyles; export type ViewMetadata = typeof _compiler_core_private_types.ViewMetadata; export var ViewMetadata: typeof r.ViewMetadata = r.ViewMetadata; +export type ComponentStillLoadingError = + typeof _compiler_core_private_types.ComponentStillLoadingError; +export var ComponentStillLoadingError: typeof r.ComponentStillLoadingError = + r.ComponentStillLoadingError; diff --git a/modules/@angular/compiler/src/animation/animation_compiler.ts b/modules/@angular/compiler/src/animation/animation_compiler.ts index 1429310c81..8c8fd5a284 100644 --- a/modules/@angular/compiler/src/animation/animation_compiler.ts +++ b/modules/@angular/compiler/src/animation/animation_compiler.ts @@ -6,8 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ -import {AUTO_STYLE, BaseException} from '@angular/core'; - import {ANY_STATE, AnimationOutput, DEFAULT_STATE, EMPTY_STATE} from '../../core_private'; import {CompileDirectiveMetadata} from '../compile_metadata'; import {StringMapWrapper} from '../facade/collection'; @@ -72,7 +70,7 @@ export class AnimationCompiler { var errorMessageStr = `Animation parsing for ${component.type.name} has failed due to the following errors:`; groupedErrors.forEach(error => errorMessageStr += `\n- ${error}`); - throw new BaseException(errorMessageStr); + throw new Error(errorMessageStr); } animationCompilationCache.set(component, compiledAnimations); diff --git a/modules/@angular/compiler/src/compile_metadata.ts b/modules/@angular/compiler/src/compile_metadata.ts index 6a90cf3c3b..9fbefde679 100644 --- a/modules/@angular/compiler/src/compile_metadata.ts +++ b/modules/@angular/compiler/src/compile_metadata.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException, ChangeDetectionStrategy, SchemaMetadata, Type, ViewEncapsulation} from '@angular/core'; +import {ChangeDetectionStrategy, SchemaMetadata, Type, ViewEncapsulation} from '@angular/core'; import {LifecycleHooks, reflector} from '../core_private'; @@ -17,7 +17,7 @@ import {getUrlScheme} from './url_resolver'; import {sanitizeIdentifier, splitAtColon} from './util'; function unimplemented(): any { - throw new BaseException('unimplemented'); + throw new Error('unimplemented'); } // group 0: "[prop] or (event) or @trigger" @@ -269,7 +269,7 @@ export class CompileIdentifierMap 0) { const errorString = rootNodesAndErrors.errors.join('\n'); - throw new BaseException(`Template parse errors:\n${errorString}`); + throw new Error(`Template parse errors:\n${errorString}`); } const templateMetadataStyles = this.normalizeStylesheet(new CompileStylesheetMetadata({ styles: templateMeta.styles, diff --git a/modules/@angular/compiler/src/directive_resolver.ts b/modules/@angular/compiler/src/directive_resolver.ts index e20280cdbb..3ea69a17db 100644 --- a/modules/@angular/compiler/src/directive_resolver.ts +++ b/modules/@angular/compiler/src/directive_resolver.ts @@ -9,7 +9,6 @@ import {ComponentMetadata, DirectiveMetadata, HostBindingMetadata, HostListenerMetadata, Injectable, InputMetadata, OutputMetadata, QueryMetadata, Type, resolveForwardRef} from '@angular/core'; import {ReflectorReader, reflector} from '../core_private'; import {StringMapWrapper} from './facade/collection'; -import {BaseException} from './facade/exceptions'; import {isPresent, stringify} from './facade/lang'; import {splitAtColon} from './util'; @@ -41,7 +40,7 @@ export class DirectiveResolver { } } if (throwIfNotFound) { - throw new BaseException(`No Directive annotation found on ${stringify(type)}`); + throw new Error(`No Directive annotation found on ${stringify(type)}`); } return null; } @@ -98,7 +97,7 @@ export class DirectiveResolver { inputs.forEach((inputDef: string) => { const publicName = this._extractPublicName(inputDef); if (inputNames.indexOf(publicName) > -1) { - throw new BaseException( + throw new Error( `Input '${publicName}' defined multiple times in '${stringify(directiveType)}'`); } }); @@ -116,7 +115,7 @@ export class DirectiveResolver { outputs.forEach((outputDef: string) => { const publicName = this._extractPublicName(outputDef); if (outputNames.indexOf(publicName) > -1) { - throw new BaseException( + throw new Error( `Output event '${publicName}' defined multiple times in '${stringify(directiveType)}'`); } }); diff --git a/modules/@angular/compiler/src/metadata_resolver.ts b/modules/@angular/compiler/src/metadata_resolver.ts index d632d7688e..da587c9a4e 100644 --- a/modules/@angular/compiler/src/metadata_resolver.ts +++ b/modules/@angular/compiler/src/metadata_resolver.ts @@ -14,7 +14,6 @@ import {StringMapWrapper} from '../src/facade/collection'; import {assertArrayOfStrings, assertInterpolationSymbols} from './assertions'; import * as cpl from './compile_metadata'; import {DirectiveResolver} from './directive_resolver'; -import {BaseException} from './facade/exceptions'; import {isArray, isBlank, isPresent, isString, stringify} from './facade/lang'; import {Identifiers, identifierToken} from './identifiers'; import {hasLifecycleHook} from './lifecycle_reflector'; @@ -161,8 +160,7 @@ export class CompileMetadataResolver { } } else { if (!selector) { - throw new BaseException( - `Directive ${stringify(directiveType)} has no selector, please add it!`); + throw new Error(`Directive ${stringify(directiveType)} has no selector, please add it!`); } } @@ -235,12 +233,12 @@ export class CompileMetadataResolver { if (importedModuleType) { let importedMeta = this.getNgModuleMetadata(importedModuleType, false); if (importedMeta === null) { - throw new BaseException( + throw new Error( `Unexpected ${this._getTypeDescriptor(importedType)} '${stringify(importedType)}' imported by the module '${stringify(moduleType)}'`); } importedModules.push(importedMeta); } else { - throw new BaseException( + throw new Error( `Unexpected value '${stringify(importedType)}' imported by the module '${stringify(moduleType)}'`); } }); @@ -249,7 +247,7 @@ export class CompileMetadataResolver { if (meta.exports) { flattenArray(meta.exports).forEach((exportedType) => { if (!isValidType(exportedType)) { - throw new BaseException( + throw new Error( `Unexpected value '${stringify(exportedType)}' exported by the module '${stringify(moduleType)}'`); } let exportedDirMeta: cpl.CompileDirectiveMetadata; @@ -262,7 +260,7 @@ export class CompileMetadataResolver { } else if (exportedModuleMeta = this.getNgModuleMetadata(exportedType, false)) { exportedModules.push(exportedModuleMeta); } else { - throw new BaseException( + throw new Error( `Unexpected ${this._getTypeDescriptor(exportedType)} '${stringify(exportedType)}' exported by the module '${stringify(moduleType)}'`); } }); @@ -275,7 +273,7 @@ export class CompileMetadataResolver { if (meta.declarations) { flattenArray(meta.declarations).forEach((declaredType) => { if (!isValidType(declaredType)) { - throw new BaseException( + throw new Error( `Unexpected value '${stringify(declaredType)}' declared by the module '${stringify(moduleType)}'`); } let declaredDirMeta: cpl.CompileDirectiveMetadata; @@ -287,7 +285,7 @@ export class CompileMetadataResolver { this._addPipeToModule( declaredPipeMeta, moduleType, transitiveModule, declaredPipes, true); } else { - throw new BaseException( + throw new Error( `Unexpected ${this._getTypeDescriptor(declaredType)} '${stringify(declaredType)}' declared by the module '${stringify(moduleType)}'`); } }); @@ -343,13 +341,13 @@ export class CompileMetadataResolver { private _verifyModule(moduleMeta: cpl.CompileNgModuleMetadata) { moduleMeta.exportedDirectives.forEach((dirMeta) => { if (!moduleMeta.transitiveModule.directivesSet.has(dirMeta.type.runtime)) { - throw new BaseException( + throw new Error( `Can't export directive ${stringify(dirMeta.type.runtime)} from ${stringify(moduleMeta.type.runtime)} as it was neither declared nor imported!`); } }); moduleMeta.exportedPipes.forEach((pipeMeta) => { if (!moduleMeta.transitiveModule.pipesSet.has(pipeMeta.type.runtime)) { - throw new BaseException( + throw new Error( `Can't export pipe ${stringify(pipeMeta.type.runtime)} from ${stringify(moduleMeta.type.runtime)} as it was neither declared nor imported!`); } }); @@ -372,7 +370,7 @@ export class CompileMetadataResolver { private _addTypeToModule(type: Type, moduleType: Type) { const oldModule = this._ngModuleOfTypes.get(type); if (oldModule && oldModule !== moduleType) { - throw new BaseException( + throw new Error( `Type ${stringify(type)} is part of the declarations of 2 modules: ${stringify(oldModule)} and ${stringify(moduleType)}!`); } this._ngModuleOfTypes.set(type, moduleType); @@ -529,7 +527,7 @@ export class CompileMetadataResolver { let depsTokens = dependenciesMetadata.map((dep) => { return dep ? stringify(dep.token) : '?'; }) .join(', '); - throw new BaseException( + throw new Error( `Can't resolve all parameters for ${stringify(typeOrFunc)}: (${depsTokens}).`); } @@ -589,7 +587,7 @@ export class CompileMetadataResolver { [])) .join(', '); - throw new BaseException( + throw new Error( `Invalid ${debugInfo ? debugInfo : 'provider'} - only instances of Provider and Type are allowed, got: [${providersInfo}]`); } if (compileProvider) { @@ -603,11 +601,10 @@ export class CompileMetadataResolver { let components: cpl.CompileTypeMetadata[] = []; let collectedIdentifiers: cpl.CompileIdentifierMetadata[] = []; if (provider.useFactory || provider.useExisting || provider.useClass) { - throw new BaseException(`The ANALYZE_FOR_ENTRY_COMPONENTS token only supports useValue!`); + throw new Error(`The ANALYZE_FOR_ENTRY_COMPONENTS token only supports useValue!`); } if (!provider.multi) { - throw new BaseException( - `The ANALYZE_FOR_ENTRY_COMPONENTS token only supports 'multi = true'!`); + throw new Error(`The ANALYZE_FOR_ENTRY_COMPONENTS token only supports 'multi = true'!`); } convertToCompileValue(provider.useValue, collectedIdentifiers); collectedIdentifiers.forEach((identifier) => { @@ -665,7 +662,7 @@ export class CompileMetadataResolver { selectors = q.varBindings.map(varName => this.getTokenMetadata(varName)); } else { if (!isPresent(q.selector)) { - throw new BaseException( + throw new Error( `Can't construct a query for the property "${propertyName}" of "${stringify(typeOrFunc)}" since the query selector wasn't defined.`); } selectors = [this.getTokenMetadata(q.selector)]; diff --git a/modules/@angular/compiler/src/ng_module_resolver.ts b/modules/@angular/compiler/src/ng_module_resolver.ts index 4e6117de4a..c4d7f77cfd 100644 --- a/modules/@angular/compiler/src/ng_module_resolver.ts +++ b/modules/@angular/compiler/src/ng_module_resolver.ts @@ -9,7 +9,6 @@ import {Injectable, NgModuleMetadata, Type} from '@angular/core'; import {ReflectorReader, reflector} from '../core_private'; -import {BaseException} from '../src/facade/exceptions'; import {isPresent, stringify} from './facade/lang'; function _isNgModuleMetadata(obj: any): obj is NgModuleMetadata { @@ -31,7 +30,7 @@ export class NgModuleResolver { return ngModuleMeta; } else { if (throwIfNotFound) { - throw new BaseException(`No NgModule metadata found for '${stringify(type)}'.`); + throw new Error(`No NgModule metadata found for '${stringify(type)}'.`); } return null; } diff --git a/modules/@angular/compiler/src/offline_compiler.ts b/modules/@angular/compiler/src/offline_compiler.ts index 438f62f975..cd46dacb2b 100644 --- a/modules/@angular/compiler/src/offline_compiler.ts +++ b/modules/@angular/compiler/src/offline_compiler.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException, SchemaMetadata} from '@angular/core'; +import {SchemaMetadata} from '@angular/core'; import {CompileDirectiveMetadata, CompileIdentifierMetadata, CompileNgModuleMetadata, CompilePipeMetadata, CompileProviderMetadata, CompileTokenMetadata, StaticSymbol, createHostComponentMeta} from './compile_metadata'; import {DirectiveNormalizer} from './directive_normalizer'; @@ -73,8 +73,7 @@ export class OfflineCompiler { const compMeta = this._metadataResolver.getDirectiveMetadata(compType); const ngModule = ngModulesSummary.ngModuleByComponent.get(compType); if (!ngModule) { - throw new BaseException( - `Cannot determine the module for component ${compMeta.type.name}!`); + throw new Error(`Cannot determine the module for component ${compMeta.type.name}!`); } return Promise .all([compMeta, ...ngModule.transitiveModule.directives].map( @@ -217,7 +216,7 @@ function _stylesModuleUrl(stylesheetUrl: string, shim: boolean, suffix: string): function _assertComponent(meta: CompileDirectiveMetadata) { if (!meta.isComponent) { - throw new BaseException(`Could not compile '${meta.type.name}' because it is not a component.`); + throw new Error(`Could not compile '${meta.type.name}' because it is not a component.`); } } diff --git a/modules/@angular/compiler/src/output/abstract_emitter.ts b/modules/@angular/compiler/src/output/abstract_emitter.ts index caa218f95e..359867cf2a 100644 --- a/modules/@angular/compiler/src/output/abstract_emitter.ts +++ b/modules/@angular/compiler/src/output/abstract_emitter.ts @@ -6,7 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException} from '@angular/core'; import {StringWrapper, isBlank, isPresent, isString} from '../facade/lang'; import * as o from './output_ast'; @@ -236,7 +235,7 @@ export abstract class AbstractEmitterVisitor implements o.StatementVisitor, o.Ex varName = CATCH_STACK_VAR.name; break; default: - throw new BaseException(`Unknown builtin variable ${ast.builtin}`); + throw new Error(`Unknown builtin variable ${ast.builtin}`); } } ctx.print(varName); @@ -332,7 +331,7 @@ export abstract class AbstractEmitterVisitor implements o.StatementVisitor, o.Ex opStr = '>='; break; default: - throw new BaseException(`Unknown operator ${ast.operator}`); + throw new Error(`Unknown operator ${ast.operator}`); } ctx.print(`(`); ast.lhs.visitExpression(this, ctx); diff --git a/modules/@angular/compiler/src/output/abstract_js_emitter.ts b/modules/@angular/compiler/src/output/abstract_js_emitter.ts index 364aa62527..326d3cd58e 100644 --- a/modules/@angular/compiler/src/output/abstract_js_emitter.ts +++ b/modules/@angular/compiler/src/output/abstract_js_emitter.ts @@ -6,7 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException} from '@angular/core'; import {isPresent} from '../facade/lang'; import {AbstractEmitterVisitor, CATCH_ERROR_VAR, CATCH_STACK_VAR, EmitterVisitorContext} from './abstract_emitter'; @@ -75,7 +74,7 @@ export abstract class AbstractJsEmitterVisitor extends AbstractEmitterVisitor { if (ast.builtin === o.BuiltinVar.This) { ctx.print('self'); } else if (ast.builtin === o.BuiltinVar.Super) { - throw new BaseException( + throw new Error( `'super' needs to be handled at a parent ast node, not at the variable level!`); } else { super.visitReadVarExpr(ast, ctx); @@ -161,7 +160,7 @@ export abstract class AbstractJsEmitterVisitor extends AbstractEmitterVisitor { name = 'bind'; break; default: - throw new BaseException(`Unknown builtin method: ${method}`); + throw new Error(`Unknown builtin method: ${method}`); } return name; } diff --git a/modules/@angular/compiler/src/output/js_emitter.ts b/modules/@angular/compiler/src/output/js_emitter.ts index b60b6bb801..c59e558417 100644 --- a/modules/@angular/compiler/src/output/js_emitter.ts +++ b/modules/@angular/compiler/src/output/js_emitter.ts @@ -6,7 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException} from '@angular/core'; import {StringWrapper, evalExpression, isBlank, isPresent, isString} from '../facade/lang'; @@ -40,7 +39,7 @@ class JsEmitterVisitor extends AbstractJsEmitterVisitor { visitExternalExpr(ast: o.ExternalExpr, ctx: EmitterVisitorContext): any { if (isBlank(ast.value.name)) { - throw new BaseException(`Internal error: unknown identifier ${ast.value}`); + throw new Error(`Internal error: unknown identifier ${ast.value}`); } if (isPresent(ast.value.moduleUrl) && ast.value.moduleUrl != this._moduleUrl) { var prefix = this.importsWithPrefixes.get(ast.value.moduleUrl); diff --git a/modules/@angular/compiler/src/output/output_ast.ts b/modules/@angular/compiler/src/output/output_ast.ts index 0d1aefbd0c..f148d402b3 100644 --- a/modules/@angular/compiler/src/output/output_ast.ts +++ b/modules/@angular/compiler/src/output/output_ast.ts @@ -6,7 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException} from '@angular/core'; import {CompileIdentifierMetadata} from '../compile_metadata'; import {StringMapWrapper} from '../facade/collection'; diff --git a/modules/@angular/compiler/src/output/output_interpreter.ts b/modules/@angular/compiler/src/output/output_interpreter.ts index 01c11b57a5..01e46d5220 100644 --- a/modules/@angular/compiler/src/output/output_interpreter.ts +++ b/modules/@angular/compiler/src/output/output_interpreter.ts @@ -6,7 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException} from '@angular/core'; import {ListWrapper} from '../facade/collection'; import {isPresent} from '../facade/lang'; @@ -104,7 +103,7 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor { } currCtx = currCtx.parent; } - throw new BaseException(`Not declared variable ${expr.name}`); + throw new Error(`Not declared variable ${expr.name}`); } visitReadVarExpr(ast: o.ReadVarExpr, ctx: _ExecutionContext): any { var varName = ast.name; @@ -121,7 +120,7 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor { varName = CATCH_STACK_VAR; break; default: - throw new BaseException(`Unknown builtin variable ${ast.builtin}`); + throw new Error(`Unknown builtin variable ${ast.builtin}`); } } var currCtx = ctx; @@ -131,7 +130,7 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor { } currCtx = currCtx.parent; } - throw new BaseException(`Not declared variable ${varName}`); + throw new Error(`Not declared variable ${varName}`); } visitWriteKeyExpr(expr: o.WriteKeyExpr, ctx: _ExecutionContext): any { var receiver = expr.receiver.visitExpression(this, ctx); @@ -163,7 +162,7 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor { result = receiver.bind(args[0]); break; default: - throw new BaseException(`Unknown builtin method ${expr.builtin}`); + throw new Error(`Unknown builtin method ${expr.builtin}`); } } else { result = receiver[expr.name].apply(receiver, args); @@ -281,7 +280,7 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor { case o.BinaryOperator.BiggerEquals: return lhs() >= rhs(); default: - throw new BaseException(`Unknown operator ${ast.operator}`); + throw new Error(`Unknown operator ${ast.operator}`); } } visitReadPropExpr(ast: o.ReadPropExpr, ctx: _ExecutionContext): any { diff --git a/modules/@angular/compiler/src/output/path_util.ts b/modules/@angular/compiler/src/output/path_util.ts index 963a3f64f2..f9f762deb4 100644 --- a/modules/@angular/compiler/src/output/path_util.ts +++ b/modules/@angular/compiler/src/output/path_util.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException, Injectable} from '@angular/core'; +import {Injectable} from '@angular/core'; import {Math, isBlank, isPresent} from '../facade/lang'; @@ -32,7 +32,7 @@ export class AssetUrl { if (allowNonMatching) { return null; } - throw new BaseException(`Url ${url} is not a valid asset: url`); + throw new Error(`Url ${url} is not a valid asset: url`); } constructor(public packageName: string, public firstLevelDir: string, public modulePath: string) { diff --git a/modules/@angular/compiler/src/output/ts_emitter.ts b/modules/@angular/compiler/src/output/ts_emitter.ts index d8fbd7331a..84b923599a 100644 --- a/modules/@angular/compiler/src/output/ts_emitter.ts +++ b/modules/@angular/compiler/src/output/ts_emitter.ts @@ -6,7 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException} from '@angular/core'; import {CompileIdentifierMetadata} from '../compile_metadata'; import {isArray, isBlank, isPresent} from '../facade/lang'; @@ -35,7 +34,7 @@ export function debugOutputAstAsTypeScript(ast: o.Statement | o.Expression | o.T } else if (ast instanceof o.Type) { ast.visitType(converter, ctx); } else { - throw new BaseException(`Don't know how to print debug info for ${ast}`); + throw new Error(`Don't know how to print debug info for ${ast}`); } }); return ctx.toSource(); @@ -249,7 +248,7 @@ class _TsEmitterVisitor extends AbstractEmitterVisitor implements o.TypeVisitor typeStr = 'string'; break; default: - throw new BaseException(`Unsupported builtin type ${type.name}`); + throw new Error(`Unsupported builtin type ${type.name}`); } ctx.print(typeStr); return null; @@ -286,7 +285,7 @@ class _TsEmitterVisitor extends AbstractEmitterVisitor implements o.TypeVisitor name = 'bind'; break; default: - throw new BaseException(`Unknown builtin method: ${method}`); + throw new Error(`Unknown builtin method: ${method}`); } return name; } @@ -302,7 +301,7 @@ class _TsEmitterVisitor extends AbstractEmitterVisitor implements o.TypeVisitor private _visitIdentifier( value: CompileIdentifierMetadata, typeParams: o.Type[], ctx: EmitterVisitorContext): void { if (isBlank(value.name)) { - throw new BaseException(`Internal error: unknown identifier ${value}`); + throw new Error(`Internal error: unknown identifier ${value}`); } if (isPresent(value.moduleUrl) && value.moduleUrl != this._moduleUrl) { var prefix = this.importsWithPrefixes.get(value.moduleUrl); diff --git a/modules/@angular/compiler/src/output/value_util.ts b/modules/@angular/compiler/src/output/value_util.ts index 4accbde355..9b0df14bc0 100644 --- a/modules/@angular/compiler/src/output/value_util.ts +++ b/modules/@angular/compiler/src/output/value_util.ts @@ -6,7 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException} from '@angular/core'; import {CompileIdentifierMetadata} from '../compile_metadata'; import {StringMapWrapper} from '../facade/collection'; @@ -39,7 +38,7 @@ class _ValueOutputAstTransformer implements ValueTransformer { } else if (value instanceof o.Expression) { return value; } else { - throw new BaseException(`Illegal state: Don't now how to compile value ${value}`); + throw new Error(`Illegal state: Don't now how to compile value ${value}`); } } } diff --git a/modules/@angular/compiler/src/pipe_resolver.ts b/modules/@angular/compiler/src/pipe_resolver.ts index ca5ddc13e0..36fcff447f 100644 --- a/modules/@angular/compiler/src/pipe_resolver.ts +++ b/modules/@angular/compiler/src/pipe_resolver.ts @@ -10,7 +10,6 @@ import {Injectable, PipeMetadata, Type, resolveForwardRef} from '@angular/core'; import {ReflectorReader, reflector} from '../core_private'; -import {BaseException} from './facade/exceptions'; import {isPresent, stringify} from './facade/lang'; function _isPipeMetadata(type: any): boolean { @@ -40,7 +39,7 @@ export class PipeResolver { } } if (throwIfNotFound) { - throw new BaseException(`No Pipe decorator found on ${stringify(type)}`); + throw new Error(`No Pipe decorator found on ${stringify(type)}`); } return null; } diff --git a/modules/@angular/compiler/src/provider_analyzer.ts b/modules/@angular/compiler/src/provider_analyzer.ts index 337749ee1f..ed09287918 100644 --- a/modules/@angular/compiler/src/provider_analyzer.ts +++ b/modules/@angular/compiler/src/provider_analyzer.ts @@ -6,7 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException} from '@angular/core'; import {CompileDiDependencyMetadata, CompileDirectiveMetadata, CompileIdentifierMap, CompileNgModuleMetadata, CompileProviderMetadata, CompileQueryMetadata, CompileTokenMetadata, CompileTypeMetadata} from './compile_metadata'; import {ListWrapper} from './facade/collection'; @@ -303,7 +302,7 @@ export class NgModuleProviderAnalyzer { (provider) => { this._getOrCreateLocalProvider(provider.token, provider.eager); }); if (this._errors.length > 0) { const errorString = this._errors.join('\n'); - throw new BaseException(`Provider parse errors:\n${errorString}`); + throw new Error(`Provider parse errors:\n${errorString}`); } return this._transformedProviders.values(); } diff --git a/modules/@angular/compiler/src/runtime_compiler.ts b/modules/@angular/compiler/src/runtime_compiler.ts index 180358d1bc..6232644a6d 100644 --- a/modules/@angular/compiler/src/runtime_compiler.ts +++ b/modules/@angular/compiler/src/runtime_compiler.ts @@ -6,14 +6,11 @@ * found in the LICENSE file at https://angular.io/license */ -import {Compiler, ComponentFactory, ComponentStillLoadingError, Injectable, Injector, ModuleWithComponentFactories, NgModuleFactory, OptionalMetadata, Provider, SchemaMetadata, SkipSelfMetadata, Type} from '@angular/core'; - -import {Console} from '../core_private'; - +import {Compiler, ComponentFactory, Injectable, Injector, ModuleWithComponentFactories, NgModuleFactory, OptionalMetadata, Provider, SchemaMetadata, SkipSelfMetadata, Type} from '@angular/core'; +import {ComponentStillLoadingError} from '../core_private'; import {CompileDirectiveMetadata, CompileIdentifierMetadata, CompileNgModuleMetadata, CompilePipeMetadata, ProviderMeta, createHostComponentMeta} from './compile_metadata'; import {CompilerConfig} from './config'; import {DirectiveNormalizer} from './directive_normalizer'; -import {BaseException} from './facade/exceptions'; import {isBlank, stringify} from './facade/lang'; import {CompileMetadataResolver} from './metadata_resolver'; import {NgModuleCompiler} from './ng_module_compiler'; @@ -223,10 +220,10 @@ export class RuntimeCompiler implements Compiler { this._compiledTemplateCache.get(compType); if (!compiledTemplate) { if (isHost) { - throw new BaseException( + throw new Error( `Illegal state: Compiled view for component ${stringify(compType)} does not exist!`); } else { - throw new BaseException( + throw new Error( `Component ${stringify(compType)} is not part of any NgModule or the module has not been imported into your module.`); } } @@ -236,7 +233,7 @@ export class RuntimeCompiler implements Compiler { private _assertComponentLoaded(compType: any, isHost: boolean): CompiledTemplate { const compiledTemplate = this._assertComponentKnown(compType, isHost); if (compiledTemplate.loading) { - throw new BaseException( + throw new Error( `Illegal state: CompiledTemplate for ${stringify(compType)} (isHost: ${isHost}) is still loading!`); } return compiledTemplate; @@ -335,7 +332,7 @@ class CompiledTemplate { }); this.proxyViewFactory = (...args: any[]) => { if (!this._viewFactory) { - throw new BaseException( + throw new Error( `Illegal state: CompiledTemplate for ${stringify(this.compType)} is not compiled yet!`); } return this._viewFactory.apply(null, args); @@ -355,7 +352,7 @@ class CompiledTemplate { get normalizedCompMeta(): CompileDirectiveMetadata { if (this.loading) { - throw new BaseException(`Template is still loading for ${this.compType.name}!`); + throw new Error(`Template is still loading for ${this.compType.name}!`); } return this._normalizedCompMeta; } @@ -370,7 +367,7 @@ class CompiledTemplate { function assertComponent(meta: CompileDirectiveMetadata) { if (!meta.isComponent) { - throw new BaseException(`Could not compile '${meta.type.name}' because it is not a component.`); + throw new Error(`Could not compile '${meta.type.name}' because it is not a component.`); } } diff --git a/modules/@angular/compiler/src/selector.ts b/modules/@angular/compiler/src/selector.ts index 8be4dfa1e6..f64620a2d9 100644 --- a/modules/@angular/compiler/src/selector.ts +++ b/modules/@angular/compiler/src/selector.ts @@ -6,7 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException} from '@angular/core'; import {ListWrapper} from './facade/collection'; import {StringWrapper, isBlank, isPresent} from './facade/lang'; @@ -50,7 +49,7 @@ export class CssSelector { while (isPresent(match = _SELECTOR_REGEXP.exec(selector))) { if (isPresent(match[1])) { if (inNot) { - throw new BaseException('Nesting :not is not allowed in a selector'); + throw new Error('Nesting :not is not allowed in a selector'); } inNot = true; current = new CssSelector(); @@ -71,7 +70,7 @@ export class CssSelector { } if (isPresent(match[7])) { if (inNot) { - throw new BaseException('Multiple selectors in :not are not supported'); + throw new Error('Multiple selectors in :not are not supported'); } _addResult(results, cssSelector); cssSelector = current = new CssSelector(); diff --git a/modules/@angular/compiler/src/template_parser/template_parser.ts b/modules/@angular/compiler/src/template_parser/template_parser.ts index fe518c87a3..160cbb120e 100644 --- a/modules/@angular/compiler/src/template_parser/template_parser.ts +++ b/modules/@angular/compiler/src/template_parser/template_parser.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException, Inject, Injectable, OpaqueToken, Optional, SchemaMetadata, SecurityContext} from '@angular/core'; +import {Inject, Injectable, OpaqueToken, Optional, SchemaMetadata, SecurityContext} from '@angular/core'; import {Console, MAX_INTERPOLATION_VALUES} from '../../core_private'; import {CompileDirectiveMetadata, CompilePipeMetadata, CompileTokenMetadata, removeIdentifierDuplicates} from '../compile_metadata'; @@ -107,7 +107,7 @@ export class TemplateParser { } if (errors.length > 0) { const errorString = errors.join('\n'); - throw new BaseException(`Template parse errors:\n${errorString}`); + throw new Error(`Template parse errors:\n${errorString}`); } return result.templateAst; @@ -236,8 +236,7 @@ class TemplateParseVisitor implements html.Visitor { this._checkPipes(ast, sourceSpan); if (isPresent(ast) && (ast.ast).expressions.length > MAX_INTERPOLATION_VALUES) { - throw new BaseException( - `Only support at most ${MAX_INTERPOLATION_VALUES} interpolation values!`); + throw new Error(`Only support at most ${MAX_INTERPOLATION_VALUES} interpolation values!`); } return ast; } catch (e) { diff --git a/modules/@angular/compiler/src/view_compiler/compile_element.ts b/modules/@angular/compiler/src/view_compiler/compile_element.ts index 5707aa1b35..005ffad164 100644 --- a/modules/@angular/compiler/src/view_compiler/compile_element.ts +++ b/modules/@angular/compiler/src/view_compiler/compile_element.ts @@ -6,7 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException} from '@angular/core'; import {CompileDiDependencyMetadata, CompileDirectiveMetadata, CompileIdentifierMap, CompileIdentifierMetadata, CompileProviderMetadata, CompileQueryMetadata, CompileTokenMetadata} from '../compile_metadata'; import {ListWrapper, StringMapWrapper} from '../facade/collection'; diff --git a/modules/@angular/compiler/src/view_compiler/compile_pipe.ts b/modules/@angular/compiler/src/view_compiler/compile_pipe.ts index 1dc4c94acd..940a3ed504 100644 --- a/modules/@angular/compiler/src/view_compiler/compile_pipe.ts +++ b/modules/@angular/compiler/src/view_compiler/compile_pipe.ts @@ -6,7 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException} from '@angular/core'; import {CompilePipeMetadata} from '../compile_metadata'; import {isBlank, isPresent} from '../facade/lang'; @@ -86,7 +85,7 @@ function _findPipeMeta(view: CompileView, name: string): CompilePipeMetadata { } } if (isBlank(pipeMeta)) { - throw new BaseException( + throw new Error( `Illegal state: Could not find pipe ${name} although the parser should have detected this error!`); } return pipeMeta; diff --git a/modules/@angular/compiler/src/view_compiler/expression_converter.ts b/modules/@angular/compiler/src/view_compiler/expression_converter.ts index 3d00c9108e..62af382d28 100644 --- a/modules/@angular/compiler/src/view_compiler/expression_converter.ts +++ b/modules/@angular/compiler/src/view_compiler/expression_converter.ts @@ -6,7 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException} from '@angular/core'; import * as cdAst from '../expression_parser/ast'; import {isArray, isBlank, isPresent} from '../facade/lang'; @@ -67,13 +66,13 @@ enum _Mode { function ensureStatementMode(mode: _Mode, ast: cdAst.AST) { if (mode !== _Mode.Statement) { - throw new BaseException(`Expected a statement, but saw ${ast}`); + throw new Error(`Expected a statement, but saw ${ast}`); } } function ensureExpressionMode(mode: _Mode, ast: cdAst.AST) { if (mode !== _Mode.Expression) { - throw new BaseException(`Expected an expression, but saw ${ast}`); + throw new Error(`Expected an expression, but saw ${ast}`); } } @@ -145,7 +144,7 @@ class _AstToIrVisitor implements cdAst.AstVisitor { op = o.BinaryOperator.BiggerEquals; break; default: - throw new BaseException(`Unsupported operation ${ast.operation}`); + throw new Error(`Unsupported operation ${ast.operation}`); } return convertToStatementIfNeeded( @@ -273,7 +272,7 @@ class _AstToIrVisitor implements cdAst.AstVisitor { if (receiver === this._implicitReceiver) { var varExpr = this._nameResolver.getLocal(ast.name); if (isPresent(varExpr)) { - throw new BaseException('Cannot assign to a reference or variable!'); + throw new Error('Cannot assign to a reference or variable!'); } } return convertToStatementIfNeeded( @@ -291,7 +290,7 @@ class _AstToIrVisitor implements cdAst.AstVisitor { visitAll(asts: cdAst.AST[], mode: _Mode): any { return asts.map(ast => this.visit(ast, mode)); } visitQuote(ast: cdAst.Quote, mode: _Mode): any { - throw new BaseException('Quotes are not supported for evaluation!'); + throw new Error('Quotes are not supported for evaluation!'); } private visit(ast: cdAst.AST, mode: _Mode): any { @@ -466,7 +465,7 @@ class _AstToIrVisitor implements cdAst.AstVisitor { private releaseTemporary(temporary: o.ReadVarExpr) { this._currentTemporary--; if (temporary.name != temporaryName(this.bindingIndex, this._currentTemporary)) { - throw new BaseException(`Temporary ${temporary.name} released out of order`); + throw new Error(`Temporary ${temporary.name} released out of order`); } } } diff --git a/modules/@angular/compiler/src/view_compiler/util.ts b/modules/@angular/compiler/src/view_compiler/util.ts index dedcdd5589..add5c81fa2 100644 --- a/modules/@angular/compiler/src/view_compiler/util.ts +++ b/modules/@angular/compiler/src/view_compiler/util.ts @@ -6,7 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException} from '@angular/core'; import {CompileDirectiveMetadata, CompileTokenMetadata} from '../compile_metadata'; import {isBlank, isPresent} from '../facade/lang'; @@ -28,7 +27,7 @@ export function getPropertyInView( viewProp = viewProp.prop('parent'); } if (currView !== definedView) { - throw new BaseException( + throw new Error( `Internal error: Could not calculate a property in a parent view: ${property}`); } if (property instanceof o.ReadPropExpr) { @@ -86,7 +85,7 @@ export function createPureProxy( var pureProxyId = argCount < Identifiers.pureProxies.length ? Identifiers.pureProxies[argCount] : null; if (isBlank(pureProxyId)) { - throw new BaseException(`Unsupported number of argument for pure functions: ${argCount}`); + throw new Error(`Unsupported number of argument for pure functions: ${argCount}`); } view.createMethod.addStmt( o.THIS_EXPR.prop(pureProxyProp.name).set(o.importExpr(pureProxyId).callFn([fn])).toStmt()); diff --git a/modules/@angular/compiler/test/css_parser/css_parser_spec.ts b/modules/@angular/compiler/test/css_parser/css_parser_spec.ts index c53a99c8f5..86710adfb9 100644 --- a/modules/@angular/compiler/test/css_parser/css_parser_spec.ts +++ b/modules/@angular/compiler/test/css_parser/css_parser_spec.ts @@ -6,7 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException} from '@angular/core'; import {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '../../../core/testing/testing_internal'; import {CssBlockAst, CssBlockDefinitionRuleAst, CssBlockRuleAst, CssDefinitionAst, CssInlineRuleAst, CssKeyframeDefinitionAst, CssKeyframeRuleAst, CssMediaQueryRuleAst, CssSelectorRuleAst, CssStyleSheetAst, CssStyleValueAst} from '../../src/css_parser/css_ast'; @@ -29,7 +28,7 @@ export function main() { var output = parse(css); var errors = output.errors; if (errors.length > 0) { - throw new BaseException(errors.map((error: CssParseError) => error.msg).join(', ')); + throw new Error(errors.map((error: CssParseError) => error.msg).join(', ')); } return output.ast; } diff --git a/modules/@angular/compiler/test/css_parser/css_visitor_spec.ts b/modules/@angular/compiler/test/css_parser/css_visitor_spec.ts index 7e4171f20c..e59014822e 100644 --- a/modules/@angular/compiler/test/css_parser/css_visitor_spec.ts +++ b/modules/@angular/compiler/test/css_parser/css_visitor_spec.ts @@ -6,7 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException} from '@angular/core'; import {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '../../../core/testing/testing_internal'; import {CssAst, CssAstVisitor, CssAtRulePredicateAst, CssBlockAst, CssBlockDefinitionRuleAst, CssBlockRuleAst, CssDefinitionAst, CssInlineRuleAst, CssKeyframeDefinitionAst, CssKeyframeRuleAst, CssMediaQueryRuleAst, CssPseudoSelectorAst, CssRuleAst, CssSelectorAst, CssSelectorRuleAst, CssSimpleSelectorAst, CssStyleSheetAst, CssStyleValueAst, CssStylesBlockAst, CssUnknownRuleAst, CssUnknownTokenListAst} from '../../src/css_parser/css_ast'; @@ -122,7 +121,7 @@ export function main() { var output = new CssParser().parse(cssCode, 'some-fake-css-file.css'); var errors = output.errors; if (errors.length > 0 && !ignoreErrors) { - throw new BaseException(errors.map((error: CssParseError) => error.msg).join(', ')); + throw new Error(errors.map((error: CssParseError) => error.msg).join(', ')); } return output.ast; } diff --git a/modules/@angular/compiler/test/ml_parser/ast_spec_utils.ts b/modules/@angular/compiler/test/ml_parser/ast_spec_utils.ts index 02d341f049..6a2657d940 100644 --- a/modules/@angular/compiler/test/ml_parser/ast_spec_utils.ts +++ b/modules/@angular/compiler/test/ml_parser/ast_spec_utils.ts @@ -6,7 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException} from '@angular/core'; import * as html from '../../src/ml_parser/ast'; import {ParseTreeResult} from '../../src/ml_parser/html_parser'; import {ParseLocation} from '../../src/parse_util'; @@ -14,7 +13,7 @@ import {ParseLocation} from '../../src/parse_util'; export function humanizeDom(parseResult: ParseTreeResult, addSourceSpan: boolean = false): any[] { if (parseResult.errors.length > 0) { var errorString = parseResult.errors.join('\n'); - throw new BaseException(`Unexpected parse errors:\n${errorString}`); + throw new Error(`Unexpected parse errors:\n${errorString}`); } return humanizeNodes(parseResult.rootNodes, addSourceSpan); diff --git a/modules/@angular/compiler/test/output/output_emitter_codegen_typed.ts b/modules/@angular/compiler/test/output/output_emitter_codegen_typed.ts index e8fc5f362b..40512a0772 100644 --- a/modules/@angular/compiler/test/output/output_emitter_codegen_typed.ts +++ b/modules/@angular/compiler/test/output/output_emitter_codegen_typed.ts @@ -9,13 +9,12 @@ // ATTENTION: This file will be overwritten with generated code by main() import * as o from '@angular/compiler/src/output/output_ast'; import {TypeScriptEmitter} from '@angular/compiler/src/output/ts_emitter'; -import {BaseException} from '@angular/core'; import {print} from '../../src/facade/lang'; import {assetUrl} from '../../src/util'; function unimplemented(): any { - throw new BaseException('unimplemented'); + throw new Error('unimplemented'); } import {SimpleJsImportGenerator, codegenExportsVars, codegenStmts} from './output_emitter_util'; diff --git a/modules/@angular/compiler/test/output/output_emitter_codegen_untyped.ts b/modules/@angular/compiler/test/output/output_emitter_codegen_untyped.ts index d89bdd0337..2e36343b30 100644 --- a/modules/@angular/compiler/test/output/output_emitter_codegen_untyped.ts +++ b/modules/@angular/compiler/test/output/output_emitter_codegen_untyped.ts @@ -8,7 +8,6 @@ // ATTENTION: This file will be overwritten with generated code by main() import {JavaScriptEmitter} from '@angular/compiler/src/output/js_emitter'; -import {BaseException} from '@angular/core'; import {print} from '../../src/facade/lang'; import {assetUrl} from '../../src/util'; @@ -16,7 +15,7 @@ import {assetUrl} from '../../src/util'; import {SimpleJsImportGenerator, codegenExportsVars, codegenStmts} from './output_emitter_util'; export function getExpressions(): any { - throw new BaseException('unimplemented'); + throw new Error('unimplemented'); } // Generator diff --git a/modules/@angular/compiler/test/output/output_emitter_spec.ts b/modules/@angular/compiler/test/output/output_emitter_spec.ts index 8a8f440dde..186f1dc32f 100644 --- a/modules/@angular/compiler/test/output/output_emitter_spec.ts +++ b/modules/@angular/compiler/test/output/output_emitter_spec.ts @@ -8,7 +8,7 @@ import {interpretStatements} from '@angular/compiler/src/output/output_interpreter'; import {jitStatements} from '@angular/compiler/src/output/output_jit'; -import {BaseException, EventEmitter} from '@angular/core'; +import {EventEmitter} from '@angular/core'; import {ViewType} from '@angular/core/src/linker/view_type'; import {beforeEach, ddescribe, describe, iit, inject, it, xit} from '@angular/core/testing/testing_internal'; import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter'; @@ -179,7 +179,7 @@ export function main() { () => { expect(expressions['throwError']).toThrowError('someError'); }); it('should support catching errors', () => { - function someOperation() { throw new BaseException('Boom!'); } + function someOperation() { throw new Error('Boom!'); } var errorAndStack = expressions['catchError'](someOperation); expect(errorAndStack[0].message).toEqual('Boom!'); diff --git a/modules/@angular/compiler/test/output/output_emitter_util.ts b/modules/@angular/compiler/test/output/output_emitter_util.ts index 38d67845f2..170b733055 100644 --- a/modules/@angular/compiler/test/output/output_emitter_util.ts +++ b/modules/@angular/compiler/test/output/output_emitter_util.ts @@ -10,7 +10,8 @@ import {CompileIdentifierMetadata} from '@angular/compiler/src/compile_metadata' import * as o from '@angular/compiler/src/output/output_ast'; import {ImportGenerator} from '@angular/compiler/src/output/path_util'; import {assetUrl} from '@angular/compiler/src/util'; -import {BaseException, EventEmitter} from '@angular/core'; +import {EventEmitter} from '@angular/core'; +import {BaseError} from '@angular/core/src/facade/errors'; import {ViewType} from '@angular/core/src/linker/view_type'; export class ExternalClass { @@ -34,8 +35,8 @@ var enumIdentifier = new CompileIdentifierMetadata({ runtime: ViewType.HOST }); -var baseExceptionIdentifier = new CompileIdentifierMetadata( - {name: 'BaseException', moduleUrl: assetUrl('core'), runtime: BaseException}); +var baseErrorIdentifier = new CompileIdentifierMetadata( + {name: 'BaseError', moduleUrl: assetUrl('core', 'facade/errors'), runtime: BaseError}); export var codegenExportsVars = [ 'getExpressions', @@ -68,8 +69,8 @@ var _getExpressionsStmts: o.Statement[] = [ .toDeclStmt(), o.variable('throwError') - .set(o.fn([], [new o.ThrowStmt(o.importExpr(baseExceptionIdentifier).instantiate([o.literal( - 'someError')]))])) + .set(o.fn([], [new o.ThrowStmt( + o.importExpr(baseErrorIdentifier).instantiate([o.literal('someError')]))])) .toDeclStmt(), o.variable('catchError') diff --git a/modules/@angular/compiler/testing/metadata_overrider.ts b/modules/@angular/compiler/testing/metadata_overrider.ts index ec96f88c21..b6d90a9c30 100644 --- a/modules/@angular/compiler/testing/metadata_overrider.ts +++ b/modules/@angular/compiler/testing/metadata_overrider.ts @@ -7,7 +7,6 @@ */ import {MetadataOverride} from '@angular/core/testing'; -import {BaseException} from '../src/facade/exceptions'; import {stringify} from '../src/facade/lang'; type StringMap = { @@ -31,8 +30,7 @@ export class MetadataOverrider { if (override.set) { if (override.remove || override.add) { - throw new BaseException( - `Cannot set and add/remove ${stringify(metadataClass)} at the same time!`); + throw new Error(`Cannot set and add/remove ${stringify(metadataClass)} at the same time!`); } setMetadata(props, override.set); } diff --git a/modules/@angular/compiler/testing/resource_loader_mock.ts b/modules/@angular/compiler/testing/resource_loader_mock.ts index 0fa2009861..60b1da4b85 100644 --- a/modules/@angular/compiler/testing/resource_loader_mock.ts +++ b/modules/@angular/compiler/testing/resource_loader_mock.ts @@ -6,7 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException} from '@angular/core'; import {ResourceLoader} from '../index'; import {ListWrapper, Map} from '../src/facade/collection'; @@ -54,7 +53,7 @@ export class MockResourceLoader extends ResourceLoader { */ flush() { if (this._requests.length === 0) { - throw new BaseException('No pending requests to flush'); + throw new Error('No pending requests to flush'); } do { @@ -76,7 +75,7 @@ export class MockResourceLoader extends ResourceLoader { urls.push(expectation.url); } - throw new BaseException(`Unsatisfied requests: ${urls.join(', ')}`); + throw new Error(`Unsatisfied requests: ${urls.join(', ')}`); } private _processRequest(request: _PendingRequest) { @@ -97,7 +96,7 @@ export class MockResourceLoader extends ResourceLoader { return; } - throw new BaseException(`Unexpected request ${url}`); + throw new Error(`Unexpected request ${url}`); } } diff --git a/modules/@angular/core/index.ts b/modules/@angular/core/index.ts index 530baa5916..72c276a932 100644 --- a/modules/@angular/core/index.ts +++ b/modules/@angular/core/index.ts @@ -30,7 +30,7 @@ export {wtfCreateScope, wtfLeave, wtfStartTimeRange, wtfEndTimeRange, WtfScopeFn export {Type} from './src/type'; export {EventEmitter} from './src/facade/async'; -export {ExceptionHandler, WrappedException, BaseException} from './src/facade/exceptions'; +export {ErrorHandler} from './src/error_handler'; export * from './private_export'; export * from './src/animation/metadata'; diff --git a/modules/@angular/core/private_export.ts b/modules/@angular/core/private_export.ts index 8935111c2c..db844f5edc 100644 --- a/modules/@angular/core/private_export.ts +++ b/modules/@angular/core/private_export.ts @@ -20,6 +20,7 @@ import * as console from './src/console'; import * as debug from './src/debug/debug_renderer'; import * as provider from './src/di/provider'; import * as reflective_provider from './src/di/reflective_provider'; +import {ComponentStillLoadingError} from './src/linker/compiler'; import * as component_factory_resolver from './src/linker/component_factory_resolver'; import * as debug_context from './src/linker/debug_context'; import * as element from './src/linker/element'; @@ -40,6 +41,7 @@ import * as api from './src/render/api'; import * as security from './src/security'; import * as decorators from './src/util/decorators'; + // These generic types can't be exported within the __core_private_types__ // interface because the generic type info will be lost. So just exporting // them separately. @@ -110,6 +112,7 @@ export interface __core_private_types__ { DEFAULT_STATE: typeof DEFAULT_STATE_; EMPTY_STATE: typeof EMPTY_STATE_; FILL_STYLE_FLAG: typeof FILL_STYLE_FLAG_; + ComponentStillLoadingError: typeof ComponentStillLoadingError; } export var __core_private__ = { @@ -176,5 +179,6 @@ export var __core_private__ = { ANY_STATE: ANY_STATE_, DEFAULT_STATE: DEFAULT_STATE_, EMPTY_STATE: EMPTY_STATE_, - FILL_STYLE_FLAG: FILL_STYLE_FLAG_ + FILL_STYLE_FLAG: FILL_STYLE_FLAG_, + ComponentStillLoadingError: ComponentStillLoadingError }; diff --git a/modules/@angular/core/src/animation/animation_player.ts b/modules/@angular/core/src/animation/animation_player.ts index 6de219fd01..ed22477cd7 100644 --- a/modules/@angular/core/src/animation/animation_player.ts +++ b/modules/@angular/core/src/animation/animation_player.ts @@ -6,7 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException} from '../facade/exceptions'; import {scheduleMicroTask} from '../facade/lang'; @@ -26,10 +25,8 @@ export abstract class AnimationPlayer { abstract reset(): void; abstract setPosition(p: any /** TODO #9100 */): void; abstract getPosition(): number; - get parentPlayer(): AnimationPlayer { throw new BaseException('NOT IMPLEMENTED: Base Class'); } - set parentPlayer(player: AnimationPlayer) { - throw new BaseException('NOT IMPLEMENTED: Base Class'); - } + get parentPlayer(): AnimationPlayer { throw new Error('NOT IMPLEMENTED: Base Class'); } + set parentPlayer(player: AnimationPlayer) { throw new Error('NOT IMPLEMENTED: Base Class'); } } export class NoOpAnimationPlayer implements AnimationPlayer { diff --git a/modules/@angular/core/src/animation/metadata.ts b/modules/@angular/core/src/animation/metadata.ts index 5be9b569f1..853745d039 100644 --- a/modules/@angular/core/src/animation/metadata.ts +++ b/modules/@angular/core/src/animation/metadata.ts @@ -6,7 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException} from '../facade/exceptions'; import {NumberWrapper, isArray, isPresent, isString} from '../facade/lang'; /** @@ -102,7 +101,7 @@ export class AnimationAnimateMetadata extends AnimationMetadata { */ export abstract class AnimationWithStepsMetadata extends AnimationMetadata { constructor() { super(); } - get steps(): AnimationMetadata[] { throw new BaseException('NOT IMPLEMENTED: Base Class'); } + get steps(): AnimationMetadata[] { throw new Error('NOT IMPLEMENTED: Base Class'); } } /** diff --git a/modules/@angular/core/src/application_ref.ts b/modules/@angular/core/src/application_ref.ts index cbe08171df..30473a2e4e 100644 --- a/modules/@angular/core/src/application_ref.ts +++ b/modules/@angular/core/src/application_ref.ts @@ -6,8 +6,9 @@ * found in the LICENSE file at https://angular.io/license */ +import {ErrorHandler} from '../src/error_handler'; import {ListWrapper} from '../src/facade/collection'; -import {BaseException, ExceptionHandler, unimplemented} from '../src/facade/exceptions'; +import {unimplemented} from '../src/facade/errors'; import {isBlank, isPresent, isPromise, stringify} from '../src/facade/lang'; import {ApplicationInitStatus} from './application_init'; @@ -40,8 +41,7 @@ var _platform: PlatformRef; */ export function enableProdMode(): void { if (_runModeLocked) { - // Cannot use BaseException as that ends up importing from facade/lang. - throw new BaseException('Cannot enable prod mode after platform setup.'); + throw new Error('Cannot enable prod mode after platform setup.'); } _devMode = false; } @@ -67,7 +67,7 @@ export function isDevMode(): boolean { */ export function createPlatform(injector: Injector): PlatformRef { if (isPresent(_platform) && !_platform.destroyed) { - throw new BaseException( + throw new Error( 'There can be only one platform. Destroy the previous one to create a new one.'); } _platform = injector.get(PlatformRef); @@ -115,10 +115,10 @@ export function createPlatformFactory( export function assertPlatform(requiredToken: any): PlatformRef { var platform = getPlatform(); if (isBlank(platform)) { - throw new BaseException('No platform exists!'); + throw new Error('No platform exists!'); } if (isPresent(platform) && isBlank(platform.injector.get(requiredToken, null))) { - throw new BaseException( + throw new Error( 'A platform with a different configuration has been created. Please destroy it first.'); } return platform; @@ -221,13 +221,12 @@ export abstract class PlatformRef { get destroyed(): boolean { throw unimplemented(); } } -function _callAndReportToExceptionHandler( - exceptionHandler: ExceptionHandler, callback: () => any): any { +function _callAndReportToExceptionHandler(errorHandler: ErrorHandler, callback: () => any): any { try { const result = callback(); if (isPromise(result)) { return result.catch((e: any) => { - exceptionHandler.call(e); + errorHandler.handleError(e); // rethrow as the exception handler might not do it throw e; }); @@ -235,7 +234,7 @@ function _callAndReportToExceptionHandler( return result; } } catch (e) { - exceptionHandler.call(e); + errorHandler.handleError(e); // rethrow as the exception handler might not do it throw e; } @@ -258,7 +257,7 @@ export class PlatformRef_ extends PlatformRef { destroy() { if (this._destroyed) { - throw new BaseException('The platform has already been destroyed!'); + throw new Error('The platform has already been destroyed!'); } ListWrapper.clone(this._modules).forEach((app) => app.destroy()); this._destroyListeners.forEach((dispose) => dispose()); @@ -282,13 +281,12 @@ export class PlatformRef_ extends PlatformRef { const ngZoneInjector = ReflectiveInjector.resolveAndCreate([{provide: NgZone, useValue: ngZone}], this.injector); const moduleRef = >moduleFactory.create(ngZoneInjector); - const exceptionHandler: ExceptionHandler = moduleRef.injector.get(ExceptionHandler, null); + const exceptionHandler: ErrorHandler = moduleRef.injector.get(ErrorHandler, null); if (!exceptionHandler) { throw new Error('No ExceptionHandler. Is platform module (BrowserModule) included?'); } moduleRef.onDestroy(() => ListWrapper.remove(this._modules, moduleRef)); - ngZone.onError.subscribe( - {next: (error: any) => { exceptionHandler.call(error, error ? error.stack : null); }}); + ngZone.onError.subscribe({next: (error: any) => { exceptionHandler.handleError(error); }}); return _callAndReportToExceptionHandler(exceptionHandler, () => { const initStatus: ApplicationInitStatus = moduleRef.injector.get(ApplicationInitStatus); return initStatus.donePromise.then(() => { @@ -333,7 +331,7 @@ export class PlatformRef_ extends PlatformRef { } else if (moduleRef.instance.ngDoBootstrap) { moduleRef.instance.ngDoBootstrap(appRef); } else { - throw new BaseException( + throw new Error( `The module ${stringify(moduleRef.instance.constructor)} was bootstrapped, but it does not declare "@NgModule.bootstrap" components nor a "ngDoBootstrap" method. ` + `Please define one of these.`); } @@ -400,7 +398,7 @@ export class ApplicationRef_ extends ApplicationRef { constructor( private _zone: NgZone, private _console: Console, private _injector: Injector, - private _exceptionHandler: ExceptionHandler, + private _exceptionHandler: ErrorHandler, private _componentFactoryResolver: ComponentFactoryResolver, private _initStatus: ApplicationInitStatus, @Optional() private _testabilityRegistry: TestabilityRegistry, @@ -422,7 +420,7 @@ export class ApplicationRef_ extends ApplicationRef { bootstrap(componentOrFactory: ComponentFactory|Type): ComponentRef { if (!this._initStatus.done) { - throw new BaseException( + throw new Error( 'Cannot bootstrap as there are still asynchronous initializers running. Bootstrap components in the `ngDoBootstrap` method of the root module.'); } let componentFactory: ComponentFactory; @@ -471,7 +469,7 @@ export class ApplicationRef_ extends ApplicationRef { tick(): void { if (this._runningTick) { - throw new BaseException('ApplicationRef.tick is called recursively'); + throw new Error('ApplicationRef.tick is called recursively'); } var s = ApplicationRef_._tickScope(); diff --git a/modules/@angular/core/src/change_detection/differs/default_iterable_differ.ts b/modules/@angular/core/src/change_detection/differs/default_iterable_differ.ts index 1bec7d125a..464358ff8b 100644 --- a/modules/@angular/core/src/change_detection/differs/default_iterable_differ.ts +++ b/modules/@angular/core/src/change_detection/differs/default_iterable_differ.ts @@ -7,7 +7,6 @@ */ import {isListLikeIterable, iterateListLike} from '../../facade/collection'; -import {BaseException} from '../../facade/exceptions'; import {getMapKey, isArray, isBlank, isPresent, looseIdentical, stringify} from '../../facade/lang'; import {ChangeDetectorRef} from '../change_detector_ref'; @@ -150,7 +149,7 @@ export class DefaultIterableDiffer implements IterableDiffer { diff(collection: any): DefaultIterableDiffer { if (isBlank(collection)) collection = []; if (!isListLikeIterable(collection)) { - throw new BaseException(`Error trying to diff '${collection}'`); + throw new Error(`Error trying to diff '${collection}'`); } if (this.check(collection)) { diff --git a/modules/@angular/core/src/change_detection/differs/default_keyvalue_differ.ts b/modules/@angular/core/src/change_detection/differs/default_keyvalue_differ.ts index 5b422ee756..ec2efbaf18 100644 --- a/modules/@angular/core/src/change_detection/differs/default_keyvalue_differ.ts +++ b/modules/@angular/core/src/change_detection/differs/default_keyvalue_differ.ts @@ -7,7 +7,6 @@ */ import {StringMapWrapper} from '../../facade/collection'; -import {BaseException} from '../../facade/exceptions'; import {isJsObject, looseIdentical, stringify} from '../../facade/lang'; import {ChangeDetectorRef} from '../change_detector_ref'; @@ -76,7 +75,7 @@ export class DefaultKeyValueDiffer implements KeyValueDiffer { if (!map) { map = new Map(); } else if (!(map instanceof Map || isJsObject(map))) { - throw new BaseException(`Error trying to diff '${map}'`); + throw new Error(`Error trying to diff '${map}'`); } return this.check(map) ? this : null; diff --git a/modules/@angular/core/src/change_detection/differs/iterable_differs.ts b/modules/@angular/core/src/change_detection/differs/iterable_differs.ts index 2394e0b7a4..adfb7d539d 100644 --- a/modules/@angular/core/src/change_detection/differs/iterable_differs.ts +++ b/modules/@angular/core/src/change_detection/differs/iterable_differs.ts @@ -8,7 +8,6 @@ import {OptionalMetadata, Provider, SkipSelfMetadata} from '../../di'; import {ListWrapper} from '../../facade/collection'; -import {BaseException} from '../../facade/exceptions'; import {getTypeNameForDebugging, isBlank, isPresent} from '../../facade/lang'; import {ChangeDetectorRef} from '../change_detector_ref'; @@ -87,7 +86,7 @@ export class IterableDiffers { // Typically would occur when calling IterableDiffers.extend inside of dependencies passed // to // bootstrap(), which would override default pipes instead of extending them. - throw new BaseException('Cannot extend IterableDiffers without a parent injector'); + throw new Error('Cannot extend IterableDiffers without a parent injector'); } return IterableDiffers.create(factories, parent); }, @@ -101,7 +100,7 @@ export class IterableDiffers { if (isPresent(factory)) { return factory; } else { - throw new BaseException( + throw new Error( `Cannot find a differ supporting object '${iterable}' of type '${getTypeNameForDebugging(iterable)}'`); } } diff --git a/modules/@angular/core/src/change_detection/differs/keyvalue_differs.ts b/modules/@angular/core/src/change_detection/differs/keyvalue_differs.ts index 196bb86748..8e95821fdf 100644 --- a/modules/@angular/core/src/change_detection/differs/keyvalue_differs.ts +++ b/modules/@angular/core/src/change_detection/differs/keyvalue_differs.ts @@ -8,7 +8,6 @@ import {OptionalMetadata, Provider, SkipSelfMetadata} from '../../di'; import {ListWrapper} from '../../facade/collection'; -import {BaseException} from '../../facade/exceptions'; import {isBlank, isPresent} from '../../facade/lang'; import {ChangeDetectorRef} from '../change_detector_ref'; @@ -77,7 +76,7 @@ export class KeyValueDiffers { // Typically would occur when calling KeyValueDiffers.extend inside of dependencies passed // to // bootstrap(), which would override default pipes instead of extending them. - throw new BaseException('Cannot extend KeyValueDiffers without a parent injector'); + throw new Error('Cannot extend KeyValueDiffers without a parent injector'); } return KeyValueDiffers.create(factories, parent); }, @@ -91,7 +90,7 @@ export class KeyValueDiffers { if (isPresent(factory)) { return factory; } else { - throw new BaseException(`Cannot find a differ supporting object '${kv}'`); + throw new Error(`Cannot find a differ supporting object '${kv}'`); } } } diff --git a/modules/@angular/core/src/di.ts b/modules/@angular/core/src/di.ts index de10d17d02..37bdbfb503 100644 --- a/modules/@angular/core/src/di.ts +++ b/modules/@angular/core/src/di.ts @@ -25,5 +25,4 @@ export {ReflectiveInjector} from './di/reflective_injector'; export {Provider, TypeProvider, ValueProvider, ClassProvider, ExistingProvider, FactoryProvider} from './di/provider'; export {ResolvedReflectiveFactory, ResolvedReflectiveProvider} from './di/reflective_provider'; export {ReflectiveKey} from './di/reflective_key'; -export {NoProviderError, AbstractProviderError, CyclicDependencyError, InstantiationError, InvalidProviderError, NoAnnotationError, OutOfBoundsError} from './di/reflective_exceptions'; export {OpaqueToken} from './di/opaque_token'; diff --git a/modules/@angular/core/src/di/injector.ts b/modules/@angular/core/src/di/injector.ts index a5454857a2..6e86524f15 100644 --- a/modules/@angular/core/src/di/injector.ts +++ b/modules/@angular/core/src/di/injector.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException, unimplemented} from '../facade/exceptions'; +import {unimplemented} from '../facade/errors'; import {stringify} from '../facade/lang'; const _THROW_IF_NOT_FOUND = new Object(); @@ -15,7 +15,7 @@ export const THROW_IF_NOT_FOUND = _THROW_IF_NOT_FOUND; class _NullInjector implements Injector { get(token: any, notFoundValue: any = _THROW_IF_NOT_FOUND): any { if (notFoundValue === _THROW_IF_NOT_FOUND) { - throw new BaseException(`No provider for ${stringify(token)}!`); + throw new Error(`No provider for ${stringify(token)}!`); } return notFoundValue; } diff --git a/modules/@angular/core/src/di/reflective_errors.ts b/modules/@angular/core/src/di/reflective_errors.ts index 43428e5838..5659ddf341 100644 --- a/modules/@angular/core/src/di/reflective_errors.ts +++ b/modules/@angular/core/src/di/reflective_errors.ts @@ -7,9 +7,10 @@ */ import {ListWrapper} from '../facade/collection'; -import {BaseException, WrappedException} from '../facade/exceptions'; +import {BaseError, WrappedError} from '../facade/errors'; import {isBlank, stringify} from '../facade/lang'; import {Type} from '../type'; + import {ReflectiveInjector} from './reflective_injector'; import {ReflectiveKey} from './reflective_key'; @@ -40,7 +41,7 @@ function constructResolvingPath(keys: any[]): string { * Base class for all errors arising from misconfigured providers. * @stable */ -export class AbstractProviderError extends BaseException { +export class AbstractProviderError extends BaseError { /** @internal */ message: string; @@ -55,7 +56,7 @@ export class AbstractProviderError extends BaseException { constructor( injector: ReflectiveInjector, key: ReflectiveKey, constructResolvingMessage: Function) { - super('DI Exception'); + super('DI Error'); this.keys = [key]; this.injectors = [injector]; this.constructResolvingMessage = constructResolvingMessage; @@ -147,7 +148,7 @@ export class CyclicDependencyError extends AbstractProviderError { * ``` * @stable */ -export class InstantiationError extends WrappedException { +export class InstantiationError extends WrappedError { /** @internal */ keys: ReflectiveKey[]; @@ -157,7 +158,7 @@ export class InstantiationError extends WrappedException { constructor( injector: ReflectiveInjector, originalException: any, originalStack: any, key: ReflectiveKey) { - super('DI Exception', originalException, originalStack, null); + super('DI Error', originalException); this.keys = [key]; this.injectors = [injector]; } @@ -167,9 +168,9 @@ export class InstantiationError extends WrappedException { this.keys.push(key); } - get wrapperMessage(): string { + get message(): string { var first = stringify(ListWrapper.first(this.keys).token); - return `Error during instantiation of ${first}!${constructResolvingPath(this.keys)}.`; + return `${this.originalError.message}: Error during instantiation of ${first}!${constructResolvingPath(this.keys)}.`; } get causeKey(): ReflectiveKey { return this.keys[0]; } @@ -188,7 +189,7 @@ export class InstantiationError extends WrappedException { * ``` * @stable */ -export class InvalidProviderError extends BaseException { +export class InvalidProviderError extends BaseError { constructor(provider: any) { super(`Invalid provider - only instances of Provider and Type are allowed, got: ${provider}`); } @@ -223,7 +224,7 @@ export class InvalidProviderError extends BaseException { * ``` * @stable */ -export class NoAnnotationError extends BaseException { +export class NoAnnotationError extends BaseError { constructor(typeOrFunc: Type|Function, params: any[][]) { super(NoAnnotationError._genMessage(typeOrFunc, params)); } @@ -259,7 +260,7 @@ export class NoAnnotationError extends BaseException { * ``` * @stable */ -export class OutOfBoundsError extends BaseException { +export class OutOfBoundsError extends BaseError { constructor(index: number) { super(`Index ${index} is out-of-bounds.`); } } @@ -276,7 +277,7 @@ export class OutOfBoundsError extends BaseException { * ])).toThrowError(); * ``` */ -export class MixingMultiProvidersWithRegularProvidersError extends BaseException { +export class MixingMultiProvidersWithRegularProvidersError extends BaseError { constructor(provider1: any, provider2: any) { super( 'Cannot mix multi providers and regular providers, got: ' + provider1.toString() + ' ' + diff --git a/modules/@angular/core/src/di/reflective_injector.ts b/modules/@angular/core/src/di/reflective_injector.ts index f41dfc7f68..21bfc16937 100644 --- a/modules/@angular/core/src/di/reflective_injector.ts +++ b/modules/@angular/core/src/di/reflective_injector.ts @@ -7,13 +7,13 @@ */ import {ListWrapper} from '../facade/collection'; -import {BaseException, unimplemented} from '../facade/exceptions'; +import {unimplemented} from '../facade/errors'; import {Type} from '../type'; import {Injector, THROW_IF_NOT_FOUND} from './injector'; import {SelfMetadata, SkipSelfMetadata} from './metadata'; import {Provider} from './provider'; -import {AbstractProviderError, CyclicDependencyError, InstantiationError, NoProviderError, OutOfBoundsError} from './reflective_exceptions'; +import {AbstractProviderError, CyclicDependencyError, InstantiationError, NoProviderError, OutOfBoundsError} from './reflective_errors'; import {ReflectiveKey} from './reflective_key'; import {ReflectiveDependency, ResolvedReflectiveFactory, ResolvedReflectiveProvider, resolveReflectiveProviders} from './reflective_provider'; @@ -797,7 +797,7 @@ export class ReflectiveInjector_ implements ReflectiveInjector { d19); break; default: - throw new BaseException( + throw new Error( `Cannot instantiate '${provider.key.displayName}' because it has more than 20 dependencies`); } } catch (e) { diff --git a/modules/@angular/core/src/di/reflective_key.ts b/modules/@angular/core/src/di/reflective_key.ts index 4ad74b51f4..86b7ad4809 100644 --- a/modules/@angular/core/src/di/reflective_key.ts +++ b/modules/@angular/core/src/di/reflective_key.ts @@ -6,7 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException} from '../facade/exceptions'; import {isBlank, stringify} from '../facade/lang'; import {resolveForwardRef} from './forward_ref'; @@ -34,7 +33,7 @@ export class ReflectiveKey { */ constructor(public token: Object, public id: number) { if (isBlank(token)) { - throw new BaseException('Token must be defined!'); + throw new Error('Token must be defined!'); } } diff --git a/modules/@angular/core/src/di/reflective_provider.ts b/modules/@angular/core/src/di/reflective_provider.ts index 42e97163e5..4e877fa832 100644 --- a/modules/@angular/core/src/di/reflective_provider.ts +++ b/modules/@angular/core/src/di/reflective_provider.ts @@ -14,7 +14,7 @@ import {Type} from '../type'; import {resolveForwardRef} from './forward_ref'; import {DependencyMetadata, HostMetadata, InjectMetadata, OptionalMetadata, SelfMetadata, SkipSelfMetadata} from './metadata'; import {ClassProvider, ExistingProvider, FactoryProvider, Provider, TypeProvider, ValueProvider} from './provider'; -import {InvalidProviderError, MixingMultiProvidersWithRegularProvidersError, NoAnnotationError} from './reflective_exceptions'; +import {InvalidProviderError, MixingMultiProvidersWithRegularProvidersError, NoAnnotationError} from './reflective_errors'; import {ReflectiveKey} from './reflective_key'; diff --git a/modules/@angular/core/src/error_handler.ts b/modules/@angular/core/src/error_handler.ts index e05d0c94cb..0d5ae4877b 100644 --- a/modules/@angular/core/src/error_handler.ts +++ b/modules/@angular/core/src/error_handler.ts @@ -6,22 +6,12 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseWrappedException} from './base_wrapped_exception'; -import {isListLikeIterable} from './collection'; -import {isBlank, isPresent} from './lang'; - -class _ArrayLogger { - res: any[] = []; - log(s: any): void { this.res.push(s); } - logError(s: any): void { this.res.push(s); } - logGroup(s: any): void { this.res.push(s); } - logGroupEnd(){}; -} +import {WrappedError} from './facade/errors'; /** * Provides a hook for centralized exception handling. * - * The default implementation of `ExceptionHandler` prints error messages to the `Console`. To + * The default implementation of `ErrorHandler` prints error messages to the `Console`. To * intercept error handling, * write a custom exception handler that replaces this default as appropriate for your app. * @@ -29,112 +19,88 @@ class _ArrayLogger { * * ```javascript * - * class MyExceptionHandler implements ExceptionHandler { + * class MyExceptionHandler implements ErrorHandler { * call(error, stackTrace = null, reason = null) { * // do something with the exception * } * } * * @NgModule({ - * providers: [{provide: ExceptionHandler, useClass: MyExceptionHandler}] + * providers: [{provide: ErrorHandler, useClass: MyErrorHandler}] * }) * class MyModule {} * ``` * @stable */ -export class ExceptionHandler { - constructor(private _logger: any, private _rethrowException: boolean = true) {} +export class ErrorHandler { + /** + * @internal + */ + _console: Console = console; - static exceptionToString(exception: any, stackTrace: any = null, reason: string = null): string { - var l = new _ArrayLogger(); - var e = new ExceptionHandler(l, false); - e.call(exception, stackTrace, reason); - return l.res.join('\n'); - } + constructor(private rethrowError: boolean = true) {} - call(exception: any, stackTrace: any = null, reason: string = null): void { - var originalException = this._findOriginalException(exception); - var originalStack = this._findOriginalStack(exception); - var context = this._findContext(exception); + handleError(error: any): void { + var originalError = this._findOriginalError(error); + var originalStack = this._findOriginalStack(error); + var context = this._findContext(error); - this._logger.logGroup(`EXCEPTION: ${this._extractMessage(exception)}`); + this._console.error(`EXCEPTION: ${this._extractMessage(error)}`); - if (isPresent(stackTrace) && isBlank(originalStack)) { - this._logger.logError('STACKTRACE:'); - this._logger.logError(this._longStackTrace(stackTrace)); + if (originalError) { + this._console.error(`ORIGINAL EXCEPTION: ${this._extractMessage(originalError)}`); } - if (isPresent(reason)) { - this._logger.logError(`REASON: ${reason}`); + if (originalStack) { + this._console.error('ORIGINAL STACKTRACE:'); + this._console.error(originalStack); } - if (isPresent(originalException)) { - this._logger.logError(`ORIGINAL EXCEPTION: ${this._extractMessage(originalException)}`); + if (context) { + this._console.error('ERROR CONTEXT:'); + this._console.error(context); } - if (isPresent(originalStack)) { - this._logger.logError('ORIGINAL STACKTRACE:'); - this._logger.logError(this._longStackTrace(originalStack)); - } - - if (isPresent(context)) { - this._logger.logError('ERROR CONTEXT:'); - this._logger.logError(context); - } - - this._logger.logGroupEnd(); - // We rethrow exceptions, so operations like 'bootstrap' will result in an error - // when an exception happens. If we do not rethrow, bootstrap will always succeed. - if (this._rethrowException) throw exception; + // when an error happens. If we do not rethrow, bootstrap will always succeed. + if (this.rethrowError) throw error; } /** @internal */ - _extractMessage(exception: any): string { - return exception instanceof BaseWrappedException ? exception.wrapperMessage : - exception.toString(); + _extractMessage(error: any): string { + return error instanceof Error ? error.message : error.toString(); } /** @internal */ - _longStackTrace(stackTrace: any): any { - return isListLikeIterable(stackTrace) ? (stackTrace).join('\n\n-----async gap-----\n') : - stackTrace.toString(); - } - - /** @internal */ - _findContext(exception: any): any { - try { - if (!(exception instanceof BaseWrappedException)) return null; - return isPresent(exception.context) ? exception.context : - this._findContext(exception.originalException); - } catch (e) { - // exception.context can throw an exception. if it happens, we ignore the context. + _findContext(error: any): any { + if (error) { + return error.context ? error.context : + this._findContext((error as WrappedError).originalError); + } else { return null; } } /** @internal */ - _findOriginalException(exception: any): any { - if (!(exception instanceof BaseWrappedException)) return null; - - var e = exception.originalException; - while (e instanceof BaseWrappedException && isPresent(e.originalException)) { - e = e.originalException; + _findOriginalError(error: any): any { + var e = (error as WrappedError).originalError; + while (e && (e as WrappedError).originalError) { + e = (e as WrappedError).originalError; } return e; } /** @internal */ - _findOriginalStack(exception: any): any { - if (!(exception instanceof BaseWrappedException)) return null; + _findOriginalStack(error: any): string { + if (!(error instanceof Error)) return null; - var e = exception; - var stack = exception.originalStack; - while (e instanceof BaseWrappedException && isPresent(e.originalException)) { - e = e.originalException; - if (e instanceof BaseWrappedException && isPresent(e.originalException)) { - stack = e.originalStack; + var e: any = error; + var stack: string = e.stack; + while (e instanceof Error && (e as WrappedError).originalError) { + e = (e as WrappedError).originalError; + if (e instanceof Error && e.stack) { + stack = e.stack; } } diff --git a/modules/@angular/core/src/linker.ts b/modules/@angular/core/src/linker.ts index 3b4badc92b..12d4c98334 100644 --- a/modules/@angular/core/src/linker.ts +++ b/modules/@angular/core/src/linker.ts @@ -7,11 +7,10 @@ */ // Public API for compiler -export {COMPILER_OPTIONS, Compiler, CompilerFactory, CompilerOptions, ComponentStillLoadingError, ModuleWithComponentFactories} from './linker/compiler'; +export {COMPILER_OPTIONS, Compiler, CompilerFactory, CompilerOptions, ModuleWithComponentFactories} from './linker/compiler'; export {ComponentFactory, ComponentRef} from './linker/component_factory'; -export {ComponentFactoryResolver, NoComponentFactoryError} from './linker/component_factory_resolver'; +export {ComponentFactoryResolver} from './linker/component_factory_resolver'; export {ElementRef} from './linker/element_ref'; -export {ExpressionChangedAfterItHasBeenCheckedException} from './linker/exceptions'; export {NgModuleFactory, NgModuleRef} from './linker/ng_module_factory'; export {NgModuleFactoryLoader} from './linker/ng_module_factory_loader'; export {QueryList} from './linker/query_list'; diff --git a/modules/@angular/core/src/linker/compiler.ts b/modules/@angular/core/src/linker/compiler.ts index b0d483d142..b1f3e9cf23 100644 --- a/modules/@angular/core/src/linker/compiler.ts +++ b/modules/@angular/core/src/linker/compiler.ts @@ -7,7 +7,7 @@ */ import {OpaqueToken} from '../di'; -import {BaseException} from '../facade/exceptions'; +import {BaseError} from '../facade/errors'; import {stringify} from '../facade/lang'; import {ViewEncapsulation} from '../metadata'; import {Type} from '../type'; @@ -22,7 +22,7 @@ import {NgModuleFactory} from './ng_module_factory'; * * @stable */ -export class ComponentStillLoadingError extends BaseException { +export class ComponentStillLoadingError extends BaseError { constructor(public compType: Type) { super(`Can't compile synchronously as ${stringify(compType)} is still being loaded!`); } @@ -41,7 +41,7 @@ export class ModuleWithComponentFactories { function _throwError() { - throw new BaseException(`Runtime compiler is not loaded`); + throw new Error(`Runtime compiler is not loaded`); } /** diff --git a/modules/@angular/core/src/linker/component_factory.ts b/modules/@angular/core/src/linker/component_factory.ts index ee9ab0c03b..792ce1ee20 100644 --- a/modules/@angular/core/src/linker/component_factory.ts +++ b/modules/@angular/core/src/linker/component_factory.ts @@ -8,7 +8,7 @@ import {ChangeDetectorRef} from '../change_detection/change_detection'; import {Injector} from '../di/injector'; -import {unimplemented} from '../facade/exceptions'; +import {unimplemented} from '../facade/errors'; import {isBlank} from '../facade/lang'; import {Type} from '../type'; import {AppElement} from './element'; diff --git a/modules/@angular/core/src/linker/component_factory_resolver.ts b/modules/@angular/core/src/linker/component_factory_resolver.ts index a0b638843d..fc882b5214 100644 --- a/modules/@angular/core/src/linker/component_factory_resolver.ts +++ b/modules/@angular/core/src/linker/component_factory_resolver.ts @@ -6,17 +6,18 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException} from '../facade/exceptions'; +import {BaseError} from '../facade/errors'; import {stringify} from '../facade/lang'; import {Type} from '../type'; import {ComponentFactory} from './component_factory'; + /** * @stable */ -export class NoComponentFactoryError extends BaseException { +export class NoComponentFactoryError extends BaseError { constructor(public component: Function) { super(`No component factory found for ${stringify(component)}`); } diff --git a/modules/@angular/core/src/linker/element.ts b/modules/@angular/core/src/linker/element.ts index bc81102605..799fda72b1 100644 --- a/modules/@angular/core/src/linker/element.ts +++ b/modules/@angular/core/src/linker/element.ts @@ -8,7 +8,6 @@ import {Injector} from '../di/injector'; import {ListWrapper} from '../facade/collection'; -import {BaseException} from '../facade/exceptions'; import {isPresent} from '../facade/lang'; import {ElementRef} from './element_ref'; @@ -63,7 +62,7 @@ export class AppElement { moveView(view: AppView, currentIndex: number) { var previousIndex = this.nestedViews.indexOf(view); if (view.type === ViewType.COMPONENT) { - throw new BaseException(`Component views can't be moved!`); + throw new Error(`Component views can't be moved!`); } var nestedViews = this.nestedViews; if (nestedViews == null) { @@ -87,7 +86,7 @@ export class AppElement { attachView(view: AppView, viewIndex: number) { if (view.type === ViewType.COMPONENT) { - throw new BaseException(`Component views can't be moved!`); + throw new Error(`Component views can't be moved!`); } var nestedViews = this.nestedViews; if (nestedViews == null) { @@ -111,7 +110,7 @@ export class AppElement { detachView(viewIndex: number): AppView { var view = ListWrapper.removeAt(this.nestedViews, viewIndex); if (view.type === ViewType.COMPONENT) { - throw new BaseException(`Component views can't be moved!`); + throw new Error(`Component views can't be moved!`); } view.detach(); diff --git a/modules/@angular/core/src/linker/errors.ts b/modules/@angular/core/src/linker/errors.ts index 049af39779..2154076327 100644 --- a/modules/@angular/core/src/linker/errors.ts +++ b/modules/@angular/core/src/linker/errors.ts @@ -7,7 +7,10 @@ */ import {UNINITIALIZED} from '../change_detection/change_detection_util'; -import {BaseException, WrappedException} from '../facade/exceptions'; +import {BaseError, WrappedError} from '../facade/errors'; + +import {DebugContext} from './debug_context'; + /** @@ -37,15 +40,15 @@ import {BaseException, WrappedException} from '../facade/exceptions'; * * set prop(v) { * // this updates the parent property, which is disallowed during change detection - * // this will result in ExpressionChangedAfterItHasBeenCheckedException + * // this will result in ExpressionChangedAfterItHasBeenCheckedError * this.parent.parentProp = "updated"; * } * } * ``` * @stable */ -export class ExpressionChangedAfterItHasBeenCheckedException extends BaseException { - constructor(oldValue: any, currValue: any, context: any) { +export class ExpressionChangedAfterItHasBeenCheckedError extends BaseError { + constructor(oldValue: any, currValue: any) { let msg = `Expression has changed after it was checked. Previous value: '${oldValue}'. Current value: '${currValue}'.`; if (oldValue === UNINITIALIZED) { @@ -64,9 +67,15 @@ export class ExpressionChangedAfterItHasBeenCheckedException extends BaseExcepti * be useful for debugging. * @stable */ -export class ViewWrappedException extends WrappedException { - constructor(originalException: any, originalStack: any, context: any) { - super(`Error in ${context.source}`, originalException, originalStack, context); +export class ViewWrappedError extends WrappedError { + /** + * DebugContext + */ + context: DebugContext; + + constructor(originalError: any, context: DebugContext) { + super(`Error in ${context.source}`, originalError); + this.context = context; } } @@ -78,6 +87,6 @@ export class ViewWrappedException extends WrappedException { * This is an internal Angular error. * @stable */ -export class ViewDestroyedException extends BaseException { +export class ViewDestroyedError extends BaseError { constructor(details: string) { super(`Attempt to use a destroyed view: ${details}`); } } diff --git a/modules/@angular/core/src/linker/ng_module_factory.ts b/modules/@angular/core/src/linker/ng_module_factory.ts index 575fb63faa..3824657892 100644 --- a/modules/@angular/core/src/linker/ng_module_factory.ts +++ b/modules/@angular/core/src/linker/ng_module_factory.ts @@ -7,7 +7,7 @@ */ import {Injector, THROW_IF_NOT_FOUND} from '../di/injector'; -import {BaseException, unimplemented} from '../facade/exceptions'; +import {unimplemented} from '../facade/errors'; import {stringify} from '../facade/lang'; import {Type} from '../type'; import {ComponentFactory} from './component_factory'; @@ -107,7 +107,7 @@ export abstract class NgModuleInjector extends CodegenComponentFactoryResolve destroy(): void { if (this._destroyed) { - throw new BaseException( + throw new Error( `The ng module ${stringify(this.instance.constructor)} has already been destroyed.`); } this._destroyed = true; diff --git a/modules/@angular/core/src/linker/view.ts b/modules/@angular/core/src/linker/view.ts index de500ea5e2..0d8e4cb393 100644 --- a/modules/@angular/core/src/linker/view.ts +++ b/modules/@angular/core/src/linker/view.ts @@ -21,7 +21,7 @@ import {RenderComponentType, RenderDebugInfo, Renderer} from '../render/api'; import {DebugContext, StaticNodeDebugInfo} from './debug_context'; import {AppElement} from './element'; import {ElementInjector} from './element_injector'; -import {ExpressionChangedAfterItHasBeenCheckedException, ViewDestroyedException, ViewWrappedException} from './exceptions'; +import {ExpressionChangedAfterItHasBeenCheckedError, ViewDestroyedError, ViewWrappedError} from './errors'; import {ViewRef_} from './view_ref'; import {ViewType} from './view_type'; import {ViewUtils, ensureSlotCount, flattenNestedViewRenderNodes} from './view_utils'; @@ -357,7 +357,7 @@ export abstract class AppView { eventHandler(cb: Function): Function { return cb; } - throwDestroyedError(details: string): void { throw new ViewDestroyedException(details); } + throwDestroyedError(details: string): void { throw new ViewDestroyedError(details); } } export class DebugAppView extends AppView { @@ -376,7 +376,7 @@ export class DebugAppView extends AppView { try { return super.create(context, givenProjectableNodes, rootSelectorOrNode); } catch (e) { - this._rethrowWithContext(e, e.stack); + this._rethrowWithContext(e); throw e; } } @@ -386,7 +386,7 @@ export class DebugAppView extends AppView { try { return super.injectorGet(token, nodeIndex, notFoundResult); } catch (e) { - this._rethrowWithContext(e, e.stack); + this._rethrowWithContext(e); throw e; } } @@ -396,7 +396,7 @@ export class DebugAppView extends AppView { try { super.detach(); } catch (e) { - this._rethrowWithContext(e, e.stack); + this._rethrowWithContext(e); throw e; } } @@ -406,7 +406,7 @@ export class DebugAppView extends AppView { try { super.destroyLocal(); } catch (e) { - this._rethrowWithContext(e, e.stack); + this._rethrowWithContext(e); throw e; } } @@ -416,7 +416,7 @@ export class DebugAppView extends AppView { try { super.detectChanges(throwOnChange); } catch (e) { - this._rethrowWithContext(e, e.stack); + this._rethrowWithContext(e); throw e; } } @@ -427,13 +427,13 @@ export class DebugAppView extends AppView { return this._currentDebugContext = new DebugContext(this, nodeIndex, rowNum, colNum); } - private _rethrowWithContext(e: any, stack: any) { - if (!(e instanceof ViewWrappedException)) { - if (!(e instanceof ExpressionChangedAfterItHasBeenCheckedException)) { + private _rethrowWithContext(e: any) { + if (!(e instanceof ViewWrappedError)) { + if (!(e instanceof ExpressionChangedAfterItHasBeenCheckedError)) { this.cdMode = ChangeDetectorStatus.Errored; } if (isPresent(this._currentDebugContext)) { - throw new ViewWrappedException(e, stack, this._currentDebugContext); + throw new ViewWrappedError(e, this._currentDebugContext); } } } @@ -445,7 +445,7 @@ export class DebugAppView extends AppView { try { return superHandler(event); } catch (e) { - this._rethrowWithContext(e, e.stack); + this._rethrowWithContext(e); throw e; } }; diff --git a/modules/@angular/core/src/linker/view_container_ref.ts b/modules/@angular/core/src/linker/view_container_ref.ts index d32e046765..3680cf74f1 100644 --- a/modules/@angular/core/src/linker/view_container_ref.ts +++ b/modules/@angular/core/src/linker/view_container_ref.ts @@ -8,7 +8,7 @@ import {Injector} from '../di/injector'; import {ListWrapper} from '../facade/collection'; -import {unimplemented} from '../facade/exceptions'; +import {unimplemented} from '../facade/errors'; import {isPresent} from '../facade/lang'; import {WtfScopeFn, wtfCreateScope, wtfLeave} from '../profile/profile'; import {ComponentFactory, ComponentRef} from './component_factory'; diff --git a/modules/@angular/core/src/linker/view_ref.ts b/modules/@angular/core/src/linker/view_ref.ts index 1f0eacd908..3948a9067f 100644 --- a/modules/@angular/core/src/linker/view_ref.ts +++ b/modules/@angular/core/src/linker/view_ref.ts @@ -8,7 +8,7 @@ import {ChangeDetectorRef} from '../change_detection/change_detector_ref'; import {ChangeDetectorStatus} from '../change_detection/constants'; -import {unimplemented} from '../facade/exceptions'; +import {unimplemented} from '../facade/errors'; import {AppView} from './view'; /** diff --git a/modules/@angular/core/src/linker/view_utils.ts b/modules/@angular/core/src/linker/view_utils.ts index 87a6e120c8..3615400f78 100644 --- a/modules/@angular/core/src/linker/view_utils.ts +++ b/modules/@angular/core/src/linker/view_utils.ts @@ -11,13 +11,12 @@ import {devModeEqual} from '../change_detection/change_detection'; import {UNINITIALIZED} from '../change_detection/change_detection_util'; import {Inject, Injectable} from '../di/decorators'; import {ListWrapper} from '../facade/collection'; -import {BaseException} from '../facade/exceptions'; import {isBlank, isPresent, looseIdentical} from '../facade/lang'; import {ViewEncapsulation} from '../metadata/view'; import {RenderComponentType, Renderer, RootRenderer} from '../render/api'; import {Sanitizer} from '../security'; import {AppElement} from './element'; -import {ExpressionChangedAfterItHasBeenCheckedException} from './exceptions'; +import {ExpressionChangedAfterItHasBeenCheckedError} from './errors'; @Injectable() export class ViewUtils { @@ -124,7 +123,7 @@ export function interpolate( c3 + _toStringWithNull(a4) + c4 + _toStringWithNull(a5) + c5 + _toStringWithNull(a6) + c6 + _toStringWithNull(a7) + c7 + _toStringWithNull(a8) + c8 + _toStringWithNull(a9) + c9; default: - throw new BaseException(`Does not support more than 9 expressions`); + throw new Error(`Does not support more than 9 expressions`); } } @@ -135,7 +134,7 @@ function _toStringWithNull(v: any): string { export function checkBinding(throwOnChange: boolean, oldValue: any, newValue: any): boolean { if (throwOnChange) { if (!devModeEqual(oldValue, newValue)) { - throw new ExpressionChangedAfterItHasBeenCheckedException(oldValue, newValue, null); + throw new ExpressionChangedAfterItHasBeenCheckedError(oldValue, newValue); } return false; } else { diff --git a/modules/@angular/core/src/reflection/reflector.ts b/modules/@angular/core/src/reflection/reflector.ts index 88ed2031dc..2d4e60236c 100644 --- a/modules/@angular/core/src/reflection/reflector.ts +++ b/modules/@angular/core/src/reflection/reflector.ts @@ -7,7 +7,6 @@ */ import {Map, MapWrapper, Set, SetWrapper, StringMapWrapper} from '../facade/collection'; -import {BaseException} from '../facade/exceptions'; import {isPresent} from '../facade/lang'; import {Type} from '../type'; import {PlatformReflectionCapabilities} from './platform_reflection_capabilities'; @@ -67,7 +66,7 @@ export class Reflector extends ReflectorReader { */ listUnusedKeys(): any[] { if (this._usedKeys == null) { - throw new BaseException('Usage tracking is disabled'); + throw new Error('Usage tracking is disabled'); } var allTypes = MapWrapper.keys(this._injectableInfo); return allTypes.filter(key => !SetWrapper.has(this._usedKeys, key)); diff --git a/modules/@angular/core/src/render/api.ts b/modules/@angular/core/src/render/api.ts index 8bd010df96..41b0d515d3 100644 --- a/modules/@angular/core/src/render/api.ts +++ b/modules/@angular/core/src/render/api.ts @@ -10,7 +10,7 @@ import {AnimationKeyframe} from '../../src/animation/animation_keyframe'; import {AnimationPlayer} from '../../src/animation/animation_player'; import {AnimationStyles} from '../../src/animation/animation_styles'; import {Injector} from '../di/injector'; -import {unimplemented} from '../facade/exceptions'; +import {unimplemented} from '../facade/errors'; import {ViewEncapsulation} from '../metadata/view'; /** diff --git a/modules/@angular/core/src/testability/testability.ts b/modules/@angular/core/src/testability/testability.ts index c21c0570b3..1d6b768e6d 100644 --- a/modules/@angular/core/src/testability/testability.ts +++ b/modules/@angular/core/src/testability/testability.ts @@ -8,7 +8,6 @@ import {Injectable} from '../di/decorators'; import {Map, MapWrapper} from '../facade/collection'; -import {BaseException} from '../facade/exceptions'; import {scheduleMicroTask} from '../facade/lang'; import {NgZone} from '../zone/ng_zone'; @@ -68,7 +67,7 @@ export class Testability { decreasePendingRequestCount(): number { this._pendingCount -= 1; if (this._pendingCount < 0) { - throw new BaseException('pending async requests below zero'); + throw new Error('pending async requests below zero'); } this._runCallbacksIfReady(); return this._pendingCount; diff --git a/modules/@angular/core/src/zone/ng_zone.ts b/modules/@angular/core/src/zone/ng_zone.ts index 89a54d33ac..c4afd6501f 100644 --- a/modules/@angular/core/src/zone/ng_zone.ts +++ b/modules/@angular/core/src/zone/ng_zone.ts @@ -7,7 +7,6 @@ */ import {EventEmitter} from '../facade/async'; -import {BaseException} from '../facade/exceptions'; import {NgZoneImpl} from './ng_zone_impl'; @@ -88,12 +87,12 @@ export class NgZone { static isInAngularZone(): boolean { return NgZoneImpl.isInAngularZone(); } static assertInAngularZone(): void { if (!NgZoneImpl.isInAngularZone()) { - throw new BaseException('Expected to be in Angular Zone, but it is not!'); + throw new Error('Expected to be in Angular Zone, but it is not!'); } } static assertNotInAngularZone(): void { if (NgZoneImpl.isInAngularZone()) { - throw new BaseException('Expected to not be in Angular Zone, but it is!'); + throw new Error('Expected to not be in Angular Zone, but it is!'); } } diff --git a/modules/@angular/core/test/application_ref_spec.ts b/modules/@angular/core/test/application_ref_spec.ts index cd5aa32741..bdee2aa41c 100644 --- a/modules/@angular/core/test/application_ref_spec.ts +++ b/modules/@angular/core/test/application_ref_spec.ts @@ -8,15 +8,13 @@ import {APP_BOOTSTRAP_LISTENER, APP_INITIALIZER, ChangeDetectorRef, CompilerFactory, Component, Injector, NgModule, PlatformRef, Type} from '@angular/core'; import {ApplicationRef, ApplicationRef_} from '@angular/core/src/application_ref'; -import {Console} from '@angular/core/src/console'; +import {ErrorHandler} from '@angular/core/src/error_handler'; import {ComponentRef} from '@angular/core/src/linker/component_factory'; import {BrowserModule} from '@angular/platform-browser'; import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter'; import {DOCUMENT} from '@angular/platform-browser/src/dom/dom_tokens'; import {expect} from '@angular/platform-browser/testing/matchers'; -import {ExceptionHandler} from '../src/facade/exception_handler'; -import {BaseException} from '../src/facade/exceptions'; import {TestBed, async, inject, withModule} from '../testing'; import {SpyChangeDetectorRef} from './spies'; @@ -27,14 +25,14 @@ class SomeComponent { export function main() { describe('bootstrap', () => { - var errorLogger: _ArrayLogger; + var mockConsole: MockConsole; var fakeDoc: Document; beforeEach(() => { fakeDoc = getDOM().createHtmlDocument(); const el = getDOM().createElement('comp', fakeDoc); getDOM().appendChild(fakeDoc.body, el); - errorLogger = new _ArrayLogger(); + mockConsole = new MockConsole(); }); type CreateModuleOptions = {providers?: any[], ngDoBootstrap?: any, bootstrap?: any[]}; @@ -48,12 +46,13 @@ export function main() { } else { options = providersOrOptions || {}; } + const errorHandler = new ErrorHandler(false); + errorHandler._console = mockConsole as any; @NgModule({ providers: [ - {provide: Console, useValue: new _MockConsole()}, - {provide: ExceptionHandler, useValue: new ExceptionHandler(errorLogger, false)}, - {provide: DOCUMENT, useValue: fakeDoc}, options.providers || [] + {provide: ErrorHandler, useValue: errorHandler}, {provide: DOCUMENT, useValue: fakeDoc}, + options.providers || [] ], imports: [BrowserModule], declarations: [SomeComponent], @@ -153,7 +152,7 @@ export function main() { // we don't have an injector and therefore no way of // getting the exception handler. So // the error is only rethrown but not logged via the exception handler. - expect(errorLogger.res).toEqual([]); + expect(mockConsole.res).toEqual([]); }); })); @@ -165,7 +164,7 @@ export function main() { ])) .then(() => expect(false).toBe(true), (e) => { expect(e).toBe('Test'); - expect(errorLogger.res).toEqual(['EXCEPTION: Test']); + expect(mockConsole.res).toEqual(['EXCEPTION: Test']); }); })); @@ -206,7 +205,7 @@ export function main() { const expectedErrMsg = `The module MyModule was bootstrapped, but it does not declare "@NgModule.bootstrap" components nor a "ngDoBootstrap" method. Please define one of these.`; expect(e.message).toEqual(expectedErrMsg); - expect(errorLogger.res).toEqual(['EXCEPTION: ' + expectedErrMsg]); + expect(mockConsole.res[0]).toEqual('EXCEPTION: ' + expectedErrMsg); }); })); }); @@ -243,7 +242,7 @@ export function main() { // we don't have an injector and therefore no way of // getting the exception handler. So // the error is only rethrown but not logged via the exception handler. - expect(errorLogger.res).toEqual([]); + expect(mockConsole.res).toEqual([]); })); it('should rethrow promise errors even if the exceptionHandler is not rethrowing', @@ -255,7 +254,7 @@ export function main() { defaultPlatform.bootstrapModuleFactory(moduleFactory) .then(() => expect(false).toBe(true), (e) => { expect(e).toBe('Test'); - expect(errorLogger.res).toEqual(['EXCEPTION: Test']); + expect(mockConsole.res).toEqual(['EXCEPTION: Test']); }); })); }); @@ -266,15 +265,8 @@ export function main() { class MyComp6 { } -class _ArrayLogger { +class MockConsole { res: any[] = []; log(s: any): void { this.res.push(s); } - logError(s: any): void { this.res.push(s); } - logGroup(s: any): void { this.res.push(s); } - logGroupEnd(){}; -} - -class _MockConsole implements Console { - log(message: string) {} - warn(message: string) {} + error(s: any): void { this.res.push(s); } } diff --git a/modules/@angular/core/test/di/reflective_injector_spec.ts b/modules/@angular/core/test/di/reflective_injector_spec.ts index 4ac45b3289..15615d15f0 100644 --- a/modules/@angular/core/test/di/reflective_injector_spec.ts +++ b/modules/@angular/core/test/di/reflective_injector_spec.ts @@ -12,7 +12,6 @@ import {ReflectiveInjectorDynamicStrategy, ReflectiveInjectorInlineStrategy, Ref import {ResolvedReflectiveProvider_} from '@angular/core/src/di/reflective_provider'; import {expect} from '@angular/platform-browser/testing/matchers'; -import {BaseException} from '../../src/facade/exceptions'; import {isBlank, isPresent, stringify} from '../../src/facade/lang'; class CustomDependencyMetadata extends DependencyMetadata {} @@ -20,7 +19,7 @@ class CustomDependencyMetadata extends DependencyMetadata {} class Engine {} class BrokenEngine { - constructor() { throw new BaseException('Broken Engine'); } + constructor() { throw new Error('Broken Engine'); } } class DashboardSoftware {} @@ -332,7 +331,7 @@ export function main() { } catch (e) { expect(e.message).toContain( `Error during instantiation of Engine! (${stringify(Car)} -> Engine)`); - expect(e.originalException instanceof BaseException).toBeTruthy(); + expect(e.originalError instanceof Error).toBeTruthy(); expect(e.causeKey.token).toEqual(Engine); } }); @@ -364,7 +363,8 @@ export function main() { {provide: Engine, useFactory: (() => isBroken ? new BrokenEngine() : new Engine())} ]); - expect(() => injector.get(Car)).toThrowError(new RegExp('Error')); + expect(() => injector.get(Car)) + .toThrowError('Broken Engine: Error during instantiation of Engine! (Car -> Engine).'); isBroken = false; diff --git a/modules/@angular/core/test/error_handler_spec.ts b/modules/@angular/core/test/error_handler_spec.ts index 704c6192b2..fc207c1073 100644 --- a/modules/@angular/core/test/error_handler_spec.ts +++ b/modules/@angular/core/test/error_handler_spec.ts @@ -6,8 +6,16 @@ * found in the LICENSE file at https://angular.io/license */ -import {beforeEach, ddescribe, describe, expect, iit, inject, it, xdescribe, xit,} from '@angular/core/testing/testing_internal'; -import {BaseException, WrappedException, ExceptionHandler} from '../src/exceptions'; +import {WrappedError} from '@angular/core/src/facade/errors'; +import {DebugContext} from '@angular/core/src/linker/debug_context'; +import {ViewWrappedError} from '@angular/core/src/linker/errors'; + +import {ErrorHandler} from '../src/error_handler'; + +class MockConsole { + res: any[] = []; + error(s: any): void { this.res.push(s); } +} class _CustomException { context = 'some context'; @@ -15,74 +23,78 @@ class _CustomException { } export function main() { - describe('ExceptionHandler', () => { + function errorToString(error: any) { + var logger = new MockConsole(); + var errorHandler = new ErrorHandler(false); + errorHandler._console = logger as any; + errorHandler.handleError(error); + return logger.res.join('\n'); + } + + function getStack(error: Error): string { + try { + throw error; + } catch (e) { + return e.stack; + } + } + + describe('ErrorHandler', () => { it('should output exception', () => { - var e = ExceptionHandler.exceptionToString(new BaseException('message!')); + var e = errorToString(new Error('message!')); expect(e).toContain('message!'); }); it('should output stackTrace', () => { - var e = ExceptionHandler.exceptionToString(new BaseException('message!'), 'stack!'); - expect(e).toContain('stack!'); - }); - - it('should join a long stackTrace', () => { - var e = - ExceptionHandler.exceptionToString(new BaseException('message!'), ['stack1', 'stack2']); - expect(e).toContain('stack1'); - expect(e).toContain('stack2'); - }); - - it('should output reason when present', () => { - var e = ExceptionHandler.exceptionToString(new BaseException('message!'), null, 'reason!'); - expect(e).toContain('reason!'); + var error = new Error('message!'); + var stack = getStack(error); + var e = errorToString(error); + expect(e).toContain(stack); }); describe('context', () => { - it('should print context', () => { - var e = ExceptionHandler.exceptionToString( - new WrappedException('message!', null, null, 'context!')); - expect(e).toContain('context!'); - }); - it('should print nested context', () => { - var original = new WrappedException('message!', null, null, 'context!'); - var e = ExceptionHandler.exceptionToString(new WrappedException('message', original)); - expect(e).toContain('context!'); - }); - - it('should not print context when the passed-in exception is not a BaseException', () => { - var e = ExceptionHandler.exceptionToString(new _CustomException()); - expect(e).not.toContain('context'); + var cause = new Error('message!'); + var stack = getStack(cause); + var context = { + source: 'context!', + toString() { return 'Context'; } + } as any as DebugContext; + var original = new ViewWrappedError(cause, context); + var e = errorToString(new WrappedError('message', original)); + expect(e).toEqual(`EXCEPTION: message caused by: Error in context! caused by: message! +ORIGINAL EXCEPTION: message! +ORIGINAL STACKTRACE: +${stack} +ERROR CONTEXT: +Context`); }); }); describe('original exception', () => { - it('should print original exception message if available (original is BaseException)', () => { - var realOriginal = new BaseException('inner'); - var original = new WrappedException('wrapped', realOriginal); - var e = - ExceptionHandler.exceptionToString(new WrappedException('wrappedwrapped', original)); - expect(e).toContain('inner'); + it('should print original exception message if available (original is Error)', () => { + var realOriginal = new Error('inner'); + var stack = getStack(realOriginal); + var original = new WrappedError('wrapped', realOriginal); + var e = errorToString(new WrappedError('wrappedwrapped', original)); + expect(e).toContain(stack); }); - it('should print original exception message if available (original is not BaseException)', - () => { - var realOriginal = new _CustomException(); - var original = new WrappedException('wrapped', realOriginal); - var e = - ExceptionHandler.exceptionToString(new WrappedException('wrappedwrapped', original)); - expect(e).toContain('custom'); - }); + it('should print original exception message if available (original is not Error)', () => { + var realOriginal = new _CustomException(); + var original = new WrappedError('wrapped', realOriginal); + var e = errorToString(new WrappedError('wrappedwrapped', original)); + expect(e).toContain('custom'); + }); }); describe('original stack', () => { it('should print original stack if available', () => { - var realOriginal = new BaseException('inner'); - var original = new WrappedException('wrapped', realOriginal, 'originalStack'); - var e = ExceptionHandler.exceptionToString( - new WrappedException('wrappedwrapped', original, 'wrappedStack')); - expect(e).toContain('originalStack'); + var realOriginal = new Error('inner'); + var stack = getStack(realOriginal); + var original = new WrappedError('wrapped', realOriginal); + var e = errorToString(new WrappedError('wrappedwrapped', original)); + expect(e).toContain(stack); }); }); }); diff --git a/modules/@angular/core/test/fake_async_spec.ts b/modules/@angular/core/test/fake_async_spec.ts index 39cf6a6ec6..1358247ad3 100644 --- a/modules/@angular/core/test/fake_async_spec.ts +++ b/modules/@angular/core/test/fake_async_spec.ts @@ -6,7 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException} from '@angular/core'; import {discardPeriodicTasks, fakeAsync, flushMicrotasks, tick} from '@angular/core/testing'; import {Log, beforeEach, ddescribe, describe, iit, inject, it, xit} from '@angular/core/testing/testing_internal'; import {expect} from '@angular/platform-browser/testing/matchers'; @@ -93,16 +92,14 @@ export function main() { it('should complain if the test throws an exception during async calls', () => { expect(() => { fakeAsync(() => { - resolvedPromise.then((_) => { throw new BaseException('async'); }); + resolvedPromise.then((_) => { throw new Error('async'); }); flushMicrotasks(); })(); - }).toThrowError('Uncaught (in promise): async'); + }).toThrowError('Uncaught (in promise): Error: async'); }); it('should complain if a test throws an exception', () => { - expect(() => { - fakeAsync(() => { throw new BaseException('sync'); })(); - }).toThrowError('sync'); + expect(() => { fakeAsync(() => { throw new Error('sync'); })(); }).toThrowError('sync'); }); }); diff --git a/modules/@angular/core/test/linker/change_detection_integration_spec.ts b/modules/@angular/core/test/linker/change_detection_integration_spec.ts index 1b93f63253..c8fb952d67 100644 --- a/modules/@angular/core/test/linker/change_detection_integration_spec.ts +++ b/modules/@angular/core/test/linker/change_detection_integration_spec.ts @@ -18,7 +18,6 @@ import {DomRootRenderer} from '@angular/platform-browser/src/dom/dom_renderer'; import {EventEmitter} from '../../src/facade/async'; import {StringMapWrapper} from '../../src/facade/collection'; -import {BaseException} from '../../src/facade/exceptions'; import {NumberWrapper, isBlank} from '../../src/facade/lang'; export function main() { @@ -724,7 +723,7 @@ export function main() { try { ctx.detectChanges(false); } catch (e) { - throw new BaseException('Second detectChanges() should not have run detection.'); + throw new Error('Second detectChanges() should not have run detection.'); } expect(directiveLog.filter(['ngOnInit'])).toEqual([]); })); @@ -821,7 +820,7 @@ export function main() { try { ctx.detectChanges(false); } catch (e) { - throw new BaseException('Second detectChanges() should not have run detection.'); + throw new Error('Second detectChanges() should not have run detection.'); } expect(directiveLog.filter(['ngAfterContentInit'])).toEqual([]); })); @@ -935,7 +934,7 @@ export function main() { try { ctx.detectChanges(false); } catch (e) { - throw new BaseException('Second detectChanges() should not have run detection.'); + throw new Error('Second detectChanges() should not have run detection.'); } expect(directiveLog.filter(['ngAfterViewInit'])).toEqual([]); })); @@ -1342,7 +1341,7 @@ class TestDirective implements OnInit, DoCheck, OnChanges, AfterContentInit, Aft ngOnInit() { this.log.add(this.name, 'ngOnInit'); if (this.throwOn == 'ngOnInit') { - throw new BaseException('Boom!'); + throw new Error('Boom!'); } } @@ -1352,42 +1351,42 @@ class TestDirective implements OnInit, DoCheck, OnChanges, AfterContentInit, Aft StringMapWrapper.forEach(changes, (c: SimpleChange, key: string) => r[key] = c.currentValue); this.changes = r; if (this.throwOn == 'ngOnChanges') { - throw new BaseException('Boom!'); + throw new Error('Boom!'); } } ngAfterContentInit() { this.log.add(this.name, 'ngAfterContentInit'); if (this.throwOn == 'ngAfterContentInit') { - throw new BaseException('Boom!'); + throw new Error('Boom!'); } } ngAfterContentChecked() { this.log.add(this.name, 'ngAfterContentChecked'); if (this.throwOn == 'ngAfterContentChecked') { - throw new BaseException('Boom!'); + throw new Error('Boom!'); } } ngAfterViewInit() { this.log.add(this.name, 'ngAfterViewInit'); if (this.throwOn == 'ngAfterViewInit') { - throw new BaseException('Boom!'); + throw new Error('Boom!'); } } ngAfterViewChecked() { this.log.add(this.name, 'ngAfterViewChecked'); if (this.throwOn == 'ngAfterViewChecked') { - throw new BaseException('Boom!'); + throw new Error('Boom!'); } } ngOnDestroy() { this.log.add(this.name, 'ngOnDestroy'); if (this.throwOn == 'ngOnDestroy') { - throw new BaseException('Boom!'); + throw new Error('Boom!'); } } } diff --git a/modules/@angular/core/test/linker/entry_components_integration_spec.ts b/modules/@angular/core/test/linker/entry_components_integration_spec.ts index 3d8a1234af..9c7a9b76e1 100644 --- a/modules/@angular/core/test/linker/entry_components_integration_spec.ts +++ b/modules/@angular/core/test/linker/entry_components_integration_spec.ts @@ -6,8 +6,10 @@ * found in the LICENSE file at https://angular.io/license */ -import {ANALYZE_FOR_ENTRY_COMPONENTS, Component, ComponentFactoryResolver, NoComponentFactoryError, forwardRef} from '@angular/core'; +import {ANALYZE_FOR_ENTRY_COMPONENTS, Component, ComponentFactoryResolver, forwardRef} from '@angular/core'; +import {NoComponentFactoryError} from '@angular/core/src/linker/component_factory_resolver'; import {TestBed} from '@angular/core/testing'; + import {Console} from '../../src/console'; diff --git a/modules/@angular/core/test/linker/integration_spec.ts b/modules/@angular/core/test/linker/integration_spec.ts index a533dc46b9..cd36841e15 100644 --- a/modules/@angular/core/test/linker/integration_spec.ts +++ b/modules/@angular/core/test/linker/integration_spec.ts @@ -23,7 +23,6 @@ import {dispatchEvent, el} from '@angular/platform-browser/testing/browser_util' import {expect} from '@angular/platform-browser/testing/matchers'; import {EventEmitter} from '../../src/facade/async'; -import {BaseException} from '../../src/facade/exceptions'; import {isBlank, isPresent, stringify} from '../../src/facade/lang'; const ANCHOR_ELEMENT = new OpaqueToken('AnchorElement'); @@ -2091,7 +2090,7 @@ class OtherDuplicateDir { @Directive({selector: 'directive-throwing-error'}) class DirectiveThrowingAnError { - constructor() { throw new BaseException('BOOM'); } + constructor() { throw new Error('BOOM'); } } @Component({ diff --git a/modules/@angular/core/test/linker/ng_module_integration_spec.ts b/modules/@angular/core/test/linker/ng_module_integration_spec.ts index 6757c767c6..6c1fc80a0a 100644 --- a/modules/@angular/core/test/linker/ng_module_integration_spec.ts +++ b/modules/@angular/core/test/linker/ng_module_integration_spec.ts @@ -11,14 +11,13 @@ import {Console} from '@angular/core/src/console'; import {ComponentFixture, TestBed, inject} from '@angular/core/testing'; import {expect} from '@angular/platform-browser/testing/matchers'; -import {BaseException} from '../../src/facade/exceptions'; import {stringify} from '../../src/facade/lang'; import {NgModuleInjector} from '../../src/linker/ng_module_factory'; class Engine {} class BrokenEngine { - constructor() { throw new BaseException('Broken Engine'); } + constructor() { throw new Error('Broken Engine'); } } class DashboardSoftware {} diff --git a/modules/@angular/core/test/zone/ng_zone_spec.ts b/modules/@angular/core/test/zone/ng_zone_spec.ts index 327081e9e4..e25df1cb93 100644 --- a/modules/@angular/core/test/zone/ng_zone_spec.ts +++ b/modules/@angular/core/test/zone/ng_zone_spec.ts @@ -6,12 +6,11 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException} from '@angular/core'; import {NgZone} from '@angular/core/src/zone/ng_zone'; import {async, fakeAsync, flushMicrotasks} from '@angular/core/testing'; import {AsyncTestCompleter, Log, beforeEach, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testing_internal'; import {browserDetection} from '@angular/platform-browser/testing/browser_util'; - +import {BaseError} from '../../src/facade/errors'; import {isPresent, scheduleMicroTask} from '../../src/facade/lang'; var needsLongerTimers = browserDetection.isSlow || browserDetection.isEdge; @@ -95,7 +94,7 @@ export function main() { setTimeout(() => { setTimeout(() => { resolve(null); - throw new BaseException('ccc'); + throw new BaseError('ccc'); }, 0); }, 0); }); @@ -118,7 +117,7 @@ export function main() { scheduleMicroTask(() => { scheduleMicroTask(() => { resolve(null); - throw new BaseException('ddd'); + throw new BaseError('ddd'); }); }); }); @@ -153,7 +152,7 @@ export function main() { setTimeout(() => { setTimeout(() => { resolve(null); - throw new BaseException('ccc'); + throw new BaseError('ccc'); }, 0); }, 0); }); @@ -720,7 +719,7 @@ function commonTests() { it('should call the on error callback when it is invoked via zone.runGuarded', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { macroTask(() => { - var exception = new BaseException('sync'); + var exception = new BaseError('sync'); _zone.runGuarded(() => { throw exception; }); @@ -733,7 +732,7 @@ function commonTests() { it('should not call the on error callback but rethrow when it is invoked via zone.run', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { macroTask(() => { - var exception = new BaseException('sync'); + var exception = new BaseError('sync'); expect(() => _zone.run(() => { throw exception; })).toThrowError('sync'); expect(_errors.length).toBe(0); @@ -743,7 +742,7 @@ function commonTests() { it('should call onError for errors from microtasks', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - var exception = new BaseException('async'); + var exception = new BaseError('async'); macroTask(() => { _zone.run(() => { scheduleMicroTask(() => { throw exception; }); }); }); diff --git a/modules/@angular/core/testing/component_fixture.ts b/modules/@angular/core/testing/component_fixture.ts index d926d6d502..4af17ad703 100644 --- a/modules/@angular/core/testing/component_fixture.ts +++ b/modules/@angular/core/testing/component_fixture.ts @@ -7,7 +7,6 @@ */ import {ChangeDetectorRef, ComponentRef, DebugElement, ElementRef, NgZone, getDebugNode} from '../index'; -import {BaseException} from '../src/facade/exceptions'; import {scheduleMicroTask} from '../src/facade/lang'; import {tick} from './fake_async'; @@ -146,7 +145,7 @@ export class ComponentFixture { */ autoDetectChanges(autoDetect: boolean = true) { if (this.ngZone == null) { - throw new BaseException('Cannot call autoDetectChanges when ComponentFixtureNoNgZone is set'); + throw new Error('Cannot call autoDetectChanges when ComponentFixtureNoNgZone is set'); } this._autoDetect = autoDetect; this.detectChanges(); diff --git a/modules/@angular/core/testing/fake_async.ts b/modules/@angular/core/testing/fake_async.ts index 924f7f08ff..673e6f3d80 100644 --- a/modules/@angular/core/testing/fake_async.ts +++ b/modules/@angular/core/testing/fake_async.ts @@ -6,7 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException} from '../index'; const FakeAsyncTestZoneSpec = (Zone as any)['FakeAsyncTestZoneSpec']; @@ -53,13 +52,13 @@ export function fakeAsync(fn: Function): (...args: any[]) => any { return function(...args: any[]) { const proxyZoneSpec = ProxyZoneSpec.assertPresent(); if (_inFakeAsyncCall) { - throw new BaseException('fakeAsync() calls can not be nested'); + throw new Error('fakeAsync() calls can not be nested'); } _inFakeAsyncCall = true; try { if (!_fakeAsyncTestZoneSpec) { if (proxyZoneSpec.getDelegate() instanceof FakeAsyncTestZoneSpec) { - throw new BaseException('fakeAsync() calls can not be nested'); + throw new Error('fakeAsync() calls can not be nested'); } _fakeAsyncTestZoneSpec = new FakeAsyncTestZoneSpec(); @@ -76,13 +75,13 @@ export function fakeAsync(fn: Function): (...args: any[]) => any { } if (_fakeAsyncTestZoneSpec.pendingPeriodicTimers.length > 0) { - throw new BaseException( + throw new Error( `${_fakeAsyncTestZoneSpec.pendingPeriodicTimers.length} ` + `periodic timer(s) still in the queue.`); } if (_fakeAsyncTestZoneSpec.pendingTimers.length > 0) { - throw new BaseException( + throw new Error( `${_fakeAsyncTestZoneSpec.pendingTimers.length} timer(s) still in the queue.`); } return res; diff --git a/modules/@angular/core/testing/test_bed.ts b/modules/@angular/core/testing/test_bed.ts index 9169309191..3e873d583e 100644 --- a/modules/@angular/core/testing/test_bed.ts +++ b/modules/@angular/core/testing/test_bed.ts @@ -6,9 +6,8 @@ * found in the LICENSE file at https://angular.io/license */ -import {CompilerOptions, ComponentMetadataType, ComponentStillLoadingError, DirectiveMetadataType, Injector, ModuleWithComponentFactories, NgModule, NgModuleFactory, NgModuleMetadataType, NgModuleRef, NgZone, OpaqueToken, PipeMetadataType, PlatformRef, Provider, SchemaMetadata} from '../index'; +import {CompilerOptions, ComponentMetadataType, DirectiveMetadataType, Injector, ModuleWithComponentFactories, NgModule, NgModuleFactory, NgModuleMetadataType, NgModuleRef, NgZone, OpaqueToken, PipeMetadataType, PlatformRef, Provider, SchemaMetadata} from '../index'; import {ListWrapper} from '../src/facade/collection'; -import {BaseException} from '../src/facade/exceptions'; import {FunctionWrapper, stringify} from '../src/facade/lang'; import {Type} from '../src/type'; @@ -173,7 +172,7 @@ export class TestBed implements Injector { */ initTestEnvironment(ngModule: Type, platform: PlatformRef) { if (this.platform || this.ngModule) { - throw new BaseException('Cannot set base providers because it has already been called'); + throw new Error('Cannot set base providers because it has already been called'); } this.platform = platform; this.ngModule = ngModule; @@ -256,7 +255,7 @@ export class TestBed implements Injector { this._moduleWithComponentFactories = this._compiler.compileModuleAndAllComponentsSync(moduleType); } catch (e) { - if (e instanceof ComponentStillLoadingError) { + if (e.compType) { throw new Error( `This test module uses the component ${stringify(e.compType)} which is using a "templateUrl", but they were never compiled. ` + `Please call "TestBed.compileComponents" before your test.`); @@ -296,7 +295,7 @@ export class TestBed implements Injector { private _assertNotInstantiated(methodName: string, methodDescription: string) { if (this._instantiated) { - throw new BaseException( + throw new Error( `Cannot ${methodDescription} when the test module has already been instantiated. ` + `Make sure you are not using \`inject\` before \`${methodName}\`.`); } @@ -344,7 +343,7 @@ export class TestBed implements Injector { const componentFactory = this._moduleWithComponentFactories.componentFactories.find( (compFactory) => compFactory.componentType === component); if (!componentFactory) { - throw new BaseException( + throw new Error( `Cannot create the component ${stringify(component)} as it was not imported into the testing module!`); } const noNgZone = this.get(ComponentFixtureNoNgZone, false); diff --git a/modules/@angular/core/testing/test_compiler.ts b/modules/@angular/core/testing/test_compiler.ts index c2cfe7c2ef..58f166c93c 100644 --- a/modules/@angular/core/testing/test_compiler.ts +++ b/modules/@angular/core/testing/test_compiler.ts @@ -7,7 +7,7 @@ */ import {Compiler, CompilerOptions, ComponentMetadataType, DirectiveMetadataType, Injector, NgModuleMetadataType, PipeMetadataType} from '../index'; -import {unimplemented} from '../src/facade/exceptions'; +import {unimplemented} from '../src/facade/errors'; import {Type} from '../src/type'; import {MetadataOverride} from './metadata_override'; diff --git a/modules/@angular/facade/src/errors.ts b/modules/@angular/facade/src/errors.ts index 8a82d9fcf3..bafd4e7182 100644 --- a/modules/@angular/facade/src/errors.ts +++ b/modules/@angular/facade/src/errors.ts @@ -6,59 +6,52 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseWrappedException} from './base_wrapped_exception'; -import {ExceptionHandler} from './exception_handler'; - -export {ExceptionHandler} from './exception_handler'; - -/** - * @stable - */ -export class BaseException extends Error { - public stack: any; - constructor(public message: string = '--') { - super(message); - this.stack = (new Error(message)).stack; - } - - toString(): string { return this.message; } -} - -/** - * Wraps an exception and provides additional context or information. - * @stable - */ -export class WrappedException extends BaseWrappedException { - private _wrapperStack: any; - - constructor( - private _wrapperMessage: string, private _originalException: any /** TODO #9100 */, - private _originalStack?: any /** TODO #9100 */, private _context?: any /** TODO #9100 */) { - super(_wrapperMessage); - this._wrapperStack = (new Error(_wrapperMessage)).stack; - } - - get wrapperMessage(): string { return this._wrapperMessage; } - - get wrapperStack(): any { return this._wrapperStack; } - - - get originalException(): any { return this._originalException; } - - get originalStack(): any { return this._originalStack; } - - - get context(): any { return this._context; } - - get message(): string { return ExceptionHandler.exceptionToString(this); } - - toString(): string { return this.message; } -} - -export function makeTypeError(message?: string): Error { - return new TypeError(message); -} - export function unimplemented(): any { - throw new BaseException('unimplemented'); + throw new Error('unimplemented'); +} + +/** + * @stable + */ +export class BaseError extends Error { + /** + * @internal + */ + _nativeError: Error; + + constructor(message: string) { + // Errors don't use current this, instead they create a new instance. + // We have to do forward all of our api to the nativeInstance. + var nativeError = super(message) as any as Error; + this._nativeError = nativeError; + } + + get message() { return this._nativeError.message; } + set message(message) { this._nativeError.message = message; } + get name() { return this._nativeError.name; } + get stack() { return (this._nativeError as any).stack; } + set stack(value) { (this._nativeError as any).stack = value; } + toString() { return this._nativeError.toString(); } +} + +/** + * @stable + */ +export class WrappedError extends BaseError { + originalError: any; + + /** + * @internal + */ + _nativeError: Error; + + constructor(message: string, error: any) { + super(`${message} caused by: ${error instanceof Error ? error.message: error }`); + this.originalError = error; + } + + get stack() { + return ((this.originalError instanceof Error ? this.originalError : this._nativeError) as any) + .stack; + } } diff --git a/modules/@angular/facade/src/lang.ts b/modules/@angular/facade/src/lang.ts index 1a06053a51..dbf29ec6f0 100644 --- a/modules/@angular/facade/src/lang.ts +++ b/modules/@angular/facade/src/lang.ts @@ -6,6 +6,8 @@ * found in the LICENSE file at https://angular.io/license */ +import {BaseError} from './errors'; + export interface BrowserNodeGlobal { Object: typeof Object; Array: typeof Array; @@ -240,14 +242,6 @@ export class StringJoiner { toString(): string { return this.parts.join(''); } } -export class NumberParseError extends Error { - name: string; - - constructor(public message: string) { super(); } - - toString(): string { return this.message; } -} - export class NumberWrapper { static toFixed(n: number, fractionDigits: number): string { return n.toFixed(fractionDigits); } @@ -257,7 +251,7 @@ export class NumberWrapper { static parseIntAutoRadix(text: string): number { var result: number = parseInt(text); if (isNaN(result)) { - throw new NumberParseError('Invalid integer literal when parsing ' + text); + throw new Error('Invalid integer literal when parsing ' + text); } return result; } @@ -277,8 +271,7 @@ export class NumberWrapper { return result; } } - throw new NumberParseError( - 'Invalid integer literal when parsing ' + text + ' in base ' + radix); + throw new Error('Invalid integer literal when parsing ' + text + ' in base ' + radix); } // TODO: NaN is a valid literal but is returned by parseFloat to indicate an error. diff --git a/modules/@angular/forms/src/directives/abstract_control_directive.ts b/modules/@angular/forms/src/directives/abstract_control_directive.ts index a29864a9f8..ef3f1765f8 100644 --- a/modules/@angular/forms/src/directives/abstract_control_directive.ts +++ b/modules/@angular/forms/src/directives/abstract_control_directive.ts @@ -6,7 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException} from '@angular/core'; import {Observable} from '../facade/async'; import {isPresent} from '../facade/lang'; import {AbstractControl} from '../model'; @@ -19,7 +18,7 @@ import {AbstractControl} from '../model'; * @stable */ export abstract class AbstractControlDirective { - get control(): AbstractControl { throw new BaseException('unimplemented'); } + get control(): AbstractControl { throw new Error('unimplemented'); } get value(): any { return isPresent(this.control) ? this.control.value : null; } diff --git a/modules/@angular/forms/src/directives/ng_control.ts b/modules/@angular/forms/src/directives/ng_control.ts index b2f23a9d49..bec931662d 100644 --- a/modules/@angular/forms/src/directives/ng_control.ts +++ b/modules/@angular/forms/src/directives/ng_control.ts @@ -6,14 +6,13 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException} from '@angular/core'; import {AbstractControlDirective} from './abstract_control_directive'; import {ControlValueAccessor} from './control_value_accessor'; import {AsyncValidatorFn, ValidatorFn} from './validators'; function unimplemented(): any { - throw new BaseException('unimplemented'); + throw new Error('unimplemented'); } /** diff --git a/modules/@angular/forms/src/directives/ng_model.ts b/modules/@angular/forms/src/directives/ng_model.ts index 062e53efed..5e96bcf857 100644 --- a/modules/@angular/forms/src/directives/ng_model.ts +++ b/modules/@angular/forms/src/directives/ng_model.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException, Directive, Host, Inject, Input, OnChanges, OnDestroy, Optional, Output, Self, SimpleChanges, forwardRef} from '@angular/core'; +import {Directive, Host, Inject, Input, OnChanges, OnDestroy, Optional, Output, Self, SimpleChanges, forwardRef} from '@angular/core'; import {EventEmitter} from '../facade/async'; import {FormControl} from '../model'; diff --git a/modules/@angular/forms/src/directives/ng_model_group.ts b/modules/@angular/forms/src/directives/ng_model_group.ts index d542058625..f1c42545fe 100644 --- a/modules/@angular/forms/src/directives/ng_model_group.ts +++ b/modules/@angular/forms/src/directives/ng_model_group.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException, Directive, Host, Inject, Input, OnDestroy, OnInit, Optional, Self, SkipSelf, forwardRef} from '@angular/core'; +import {Directive, Host, Inject, Input, OnDestroy, OnInit, Optional, Self, SkipSelf, forwardRef} from '@angular/core'; import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../validators'; diff --git a/modules/@angular/forms/src/directives/radio_control_value_accessor.ts b/modules/@angular/forms/src/directives/radio_control_value_accessor.ts index fd9e069001..98a2dc4280 100644 --- a/modules/@angular/forms/src/directives/radio_control_value_accessor.ts +++ b/modules/@angular/forms/src/directives/radio_control_value_accessor.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException, Directive, ElementRef, Injectable, Injector, Input, OnDestroy, OnInit, Renderer, forwardRef} from '@angular/core'; +import {Directive, ElementRef, Injectable, Injector, Input, OnDestroy, OnInit, Renderer, forwardRef} from '@angular/core'; import {ListWrapper} from '../facade/collection'; import {isPresent} from '../facade/lang'; @@ -139,7 +139,7 @@ export class RadioControlValueAccessor implements ControlValueAccessor, } private _throwNameError(): void { - throw new BaseException(` + throw new Error(` If you define both a name and a formControlName attribute on your radio button, their values must match. Ex: `); diff --git a/modules/@angular/forms/src/directives/reactive_directives/form_group_directive.ts b/modules/@angular/forms/src/directives/reactive_directives/form_group_directive.ts index d5d69c5fb4..14d140c5a0 100644 --- a/modules/@angular/forms/src/directives/reactive_directives/form_group_directive.ts +++ b/modules/@angular/forms/src/directives/reactive_directives/form_group_directive.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException, Directive, Inject, Input, OnChanges, Optional, Output, Self, SimpleChanges, forwardRef} from '@angular/core'; +import {Directive, Inject, Input, OnChanges, Optional, Output, Self, SimpleChanges, forwardRef} from '@angular/core'; import {EventEmitter} from '../../facade/async'; import {ListWrapper, StringMapWrapper} from '../../facade/collection'; diff --git a/modules/@angular/forms/src/directives/reactive_errors.ts b/modules/@angular/forms/src/directives/reactive_errors.ts index 1f73f963c4..0f9286fb8e 100644 --- a/modules/@angular/forms/src/directives/reactive_errors.ts +++ b/modules/@angular/forms/src/directives/reactive_errors.ts @@ -6,13 +6,12 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException} from '@angular/core'; import {FormErrorExamples as Examples} from './error_examples'; export class ReactiveErrors { static controlParentException(): void { - throw new BaseException( + throw new Error( `formControlName must be used with a parent formGroup directive. You'll want to add a formGroup directive and pass it an existing FormGroup instance (you can create one in your class). @@ -22,7 +21,7 @@ export class ReactiveErrors { } static ngModelGroupException(): void { - throw new BaseException( + throw new Error( `formControlName cannot be used with an ngModelGroup parent. It is only compatible with parents that also have a "form" prefix: formGroupName, formArrayName, or formGroup. @@ -35,7 +34,7 @@ export class ReactiveErrors { ${Examples.ngModelGroup}`); } static missingFormException(): void { - throw new BaseException(`formGroup expects a FormGroup instance. Please pass one in. + throw new Error(`formGroup expects a FormGroup instance. Please pass one in. Example: @@ -43,7 +42,7 @@ export class ReactiveErrors { } static groupParentException(): void { - throw new BaseException( + throw new Error( `formGroupName must be used with a parent formGroup directive. You'll want to add a formGroup directive and pass it an existing FormGroup instance (you can create one in your class). @@ -53,7 +52,7 @@ export class ReactiveErrors { } static arrayParentException(): void { - throw new BaseException( + throw new Error( `formArrayName must be used with a parent formGroup directive. You'll want to add a formGroup directive and pass it an existing FormGroup instance (you can create one in your class). diff --git a/modules/@angular/forms/src/directives/shared.ts b/modules/@angular/forms/src/directives/shared.ts index 0ee8a9d7c9..12b753073a 100644 --- a/modules/@angular/forms/src/directives/shared.ts +++ b/modules/@angular/forms/src/directives/shared.ts @@ -6,7 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException} from '@angular/core'; import {ListWrapper, StringMapWrapper} from '../facade/collection'; import {hasConstructor, isBlank, isPresent, looseIdentical} from '../facade/lang'; @@ -93,7 +92,7 @@ function _throwError(dir: AbstractControlDirective, message: string): void { } else { messageEnd = 'unspecified name attribute'; } - throw new BaseException(`${message} ${messageEnd}`); + throw new Error(`${message} ${messageEnd}`); } export function composeValidators(validators: /* Array */ any[]): ValidatorFn { diff --git a/modules/@angular/forms/src/directives/template_driven_errors.ts b/modules/@angular/forms/src/directives/template_driven_errors.ts index c36e0e1d2e..2fcc0785e6 100644 --- a/modules/@angular/forms/src/directives/template_driven_errors.ts +++ b/modules/@angular/forms/src/directives/template_driven_errors.ts @@ -6,12 +6,11 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException} from '@angular/core'; import {FormErrorExamples as Examples} from './error_examples'; export class TemplateDrivenErrors { static modelParentException(): void { - throw new BaseException(` + throw new Error(` ngModel cannot be used to register form controls with a parent formGroup directive. Try using formGroup's partner directive "formControlName" instead. Example: @@ -25,7 +24,7 @@ export class TemplateDrivenErrors { } static formGroupNameException(): void { - throw new BaseException(` + throw new Error(` ngModel cannot be used to register form controls with a parent formGroupName or formArrayName directive. Option 1: Use formControlName instead of ngModel (reactive strategy): @@ -38,7 +37,7 @@ export class TemplateDrivenErrors { } static missingNameException() { - throw new BaseException( + throw new Error( `If ngModel is used within a form tag, either the name attribute must be set or the form control must be defined as 'standalone' in ngModelOptions. @@ -47,7 +46,7 @@ export class TemplateDrivenErrors { } static modelGroupParentException() { - throw new BaseException(` + throw new Error(` ngModelGroup cannot be used with a parent formGroup directive. Option 1: Use formGroupName instead of ngModelGroup (reactive strategy): diff --git a/modules/@angular/forms/src/model.ts b/modules/@angular/forms/src/model.ts index f744e51b94..159760b5ac 100644 --- a/modules/@angular/forms/src/model.ts +++ b/modules/@angular/forms/src/model.ts @@ -6,7 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException} from '@angular/core'; import {PromiseObservable} from 'rxjs/observable/PromiseObservable'; import {composeAsyncValidators, composeValidators} from './directives/shared'; @@ -645,13 +644,13 @@ export class FormGroup extends AbstractControl { /** @internal */ _throwIfControlMissing(name: string): void { if (!Object.keys(this.controls).length) { - throw new BaseException(` + throw new Error(` There are no form controls registered with this group yet. If you're using ngModel, you may want to check next tick (e.g. use setTimeout). `); } if (!this.controls[name]) { - throw new BaseException(`Cannot find form control with name: ${name}.`); + throw new Error(`Cannot find form control with name: ${name}.`); } } @@ -710,7 +709,7 @@ export class FormGroup extends AbstractControl { _checkAllValuesPresent(value: any): void { this._forEachChild((control: AbstractControl, name: string) => { if (value[name] === undefined) { - throw new BaseException(`Must supply a value for form control with name: '${name}'.`); + throw new Error(`Must supply a value for form control with name: '${name}'.`); } }); } @@ -817,13 +816,13 @@ export class FormArray extends AbstractControl { /** @internal */ _throwIfControlMissing(index: number): void { if (!this.controls.length) { - throw new BaseException(` + throw new Error(` There are no form controls registered with this array yet. If you're using ngModel, you may want to check next tick (e.g. use setTimeout). `); } if (!this.at(index)) { - throw new BaseException(`Cannot find form control at index ${index}`); + throw new Error(`Cannot find form control at index ${index}`); } } @@ -852,7 +851,7 @@ export class FormArray extends AbstractControl { _checkAllValuesPresent(value: any): void { this._forEachChild((control: AbstractControl, i: number) => { if (value[i] === undefined) { - throw new BaseException(`Must supply a value for form control at index: ${i}.`); + throw new Error(`Must supply a value for form control at index: ${i}.`); } }); } diff --git a/modules/@angular/http/src/headers.ts b/modules/@angular/http/src/headers.ts index 553fb34f86..f22466ee75 100644 --- a/modules/@angular/http/src/headers.ts +++ b/modules/@angular/http/src/headers.ts @@ -6,7 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException} from '@angular/core'; import {ListWrapper, Map, MapWrapper, StringMapWrapper, isListLikeIterable, iterateListLike} from '../src/facade/collection'; import {isBlank} from '../src/facade/lang'; @@ -163,7 +162,7 @@ export class Headers { /** * This method is not implemented. */ - entries() { throw new BaseException('"entries" method is not implemented on Headers class'); } + entries() { throw new Error('"entries" method is not implemented on Headers class'); } } // "HTTP character sets are identified by case-insensitive tokens" diff --git a/modules/@angular/http/src/http.ts b/modules/@angular/http/src/http.ts index d11a778526..7dab9ff007 100644 --- a/modules/@angular/http/src/http.ts +++ b/modules/@angular/http/src/http.ts @@ -9,7 +9,6 @@ import {Injectable} from '@angular/core'; import {Observable} from 'rxjs/Observable'; -import {makeTypeError} from '../src/facade/exceptions'; import {isPresent, isString} from '../src/facade/lang'; import {BaseRequestOptions, RequestOptions} from './base_request_options'; @@ -125,7 +124,7 @@ export class Http { } else if (url instanceof Request) { responseObservable = httpRequest(this._backend, url); } else { - throw makeTypeError('First argument must be a url string or Request instance.'); + throw new Error('First argument must be a url string or Request instance.'); } return responseObservable; } @@ -229,11 +228,11 @@ export class Jsonp extends Http { } if (url instanceof Request) { if (url.method !== RequestMethod.Get) { - makeTypeError('JSONP requests must use GET request method.'); + throw new Error('JSONP requests must use GET request method.'); } responseObservable = httpRequest(this._backend, url); } else { - throw makeTypeError('First argument must be a url string or Request instance.'); + throw new Error('First argument must be a url string or Request instance.'); } return responseObservable; } diff --git a/modules/@angular/http/src/http_utils.ts b/modules/@angular/http/src/http_utils.ts index a69fa0445c..d5d00366cf 100644 --- a/modules/@angular/http/src/http_utils.ts +++ b/modules/@angular/http/src/http_utils.ts @@ -6,7 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ -import {makeTypeError} from '../src/facade/exceptions'; import {isString} from '../src/facade/lang'; import {RequestMethod} from './enums'; @@ -20,8 +19,7 @@ export function normalizeMethodName(method: string | RequestMethod): RequestMeth (g0: string, g1: string, g2: string) => g1.toUpperCase() + g2.toLowerCase()); method = (<{[key: string]: any}>RequestMethod)[method]; if (typeof method !== 'number') - throw makeTypeError( - `Invalid request method. The method "${originalMethod}" is not supported.`); + throw new Error(`Invalid request method. The method "${originalMethod}" is not supported.`); } return method; } diff --git a/modules/@angular/http/src/static_response.ts b/modules/@angular/http/src/static_response.ts index d8f12d6d30..e423ecc12a 100644 --- a/modules/@angular/http/src/static_response.ts +++ b/modules/@angular/http/src/static_response.ts @@ -6,7 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException} from '@angular/core'; import {Json, isString} from '../src/facade/lang'; import {ResponseOptions} from './base_response_options'; diff --git a/modules/@angular/http/testing/mock_backend.ts b/modules/@angular/http/testing/mock_backend.ts index 22bc90a562..88678281a6 100644 --- a/modules/@angular/http/testing/mock_backend.ts +++ b/modules/@angular/http/testing/mock_backend.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException, Injectable} from '@angular/core'; +import {Injectable} from '@angular/core'; import {ReplaySubject} from 'rxjs/ReplaySubject'; import {Subject} from 'rxjs/Subject'; import {take} from 'rxjs/operator/take'; @@ -68,7 +68,7 @@ export class MockConnection implements Connection { */ mockRespond(res: Response) { if (this.readyState === ReadyState.Done || this.readyState === ReadyState.Cancelled) { - throw new BaseException('Connection has already been resolved'); + throw new Error('Connection has already been resolved'); } this.readyState = ReadyState.Done; this.response.next(res); @@ -214,7 +214,7 @@ export class MockBackend implements ConnectionBackend { verifyNoPendingRequests() { let pending = 0; this.pendingConnections.subscribe((c: MockConnection) => pending++); - if (pending > 0) throw new BaseException(`${pending} pending connections to be resolved`); + if (pending > 0) throw new Error(`${pending} pending connections to be resolved`); } /** @@ -233,7 +233,7 @@ export class MockBackend implements ConnectionBackend { */ createConnection(req: Request): MockConnection { if (!isPresent(req) || !(req instanceof Request)) { - throw new BaseException(`createConnection requires an instance of Request, got ${req}`); + throw new Error(`createConnection requires an instance of Request, got ${req}`); } let connection = new MockConnection(req); this.connections.next(connection); diff --git a/modules/@angular/platform-browser-dynamic/src/resource_loader/resource_loader_cache.ts b/modules/@angular/platform-browser-dynamic/src/resource_loader/resource_loader_cache.ts index 2c49321f52..a0fc6967d1 100644 --- a/modules/@angular/platform-browser-dynamic/src/resource_loader/resource_loader_cache.ts +++ b/modules/@angular/platform-browser-dynamic/src/resource_loader/resource_loader_cache.ts @@ -7,7 +7,6 @@ */ import {ResourceLoader} from '@angular/compiler'; -import {BaseException} from '@angular/core'; import {global} from '../facade/lang'; /** @@ -24,8 +23,7 @@ export class CachedResourceLoader extends ResourceLoader { super(); this._cache = (global).$templateCache; if (this._cache == null) { - throw new BaseException( - 'CachedResourceLoader: Template cache was not found in $templateCache.'); + throw new Error('CachedResourceLoader: Template cache was not found in $templateCache.'); } } diff --git a/modules/@angular/platform-browser-dynamic/test/resource_loader/resource_loader_cache_spec.ts b/modules/@angular/platform-browser-dynamic/test/resource_loader/resource_loader_cache_spec.ts index 5f77c48581..08181e783e 100644 --- a/modules/@angular/platform-browser-dynamic/test/resource_loader/resource_loader_cache_spec.ts +++ b/modules/@angular/platform-browser-dynamic/test/resource_loader/resource_loader_cache_spec.ts @@ -7,7 +7,7 @@ */ import {ResourceLoader, UrlResolver} from '@angular/compiler'; -import {BaseException, Component} from '@angular/core'; +import {Component} from '@angular/core'; import {TestBed, async, fakeAsync, tick} from '@angular/core/testing'; import {expect} from '@angular/platform-browser/testing/matchers'; @@ -51,7 +51,7 @@ export function main() { it('should reject the Promise on failure', async(() => { resourceLoader = new CachedResourceLoader(); resourceLoader.get('unknown.html') - .then((text) => { throw new BaseException('Not expected to succeed.'); }) + .then((text) => { throw new Error('Not expected to succeed.'); }) .catch((error) => {/** success */}); })); diff --git a/modules/@angular/platform-browser/src/browser.ts b/modules/@angular/platform-browser/src/browser.ts index 77683ea037..9e3d41ba5f 100644 --- a/modules/@angular/platform-browser/src/browser.ts +++ b/modules/@angular/platform-browser/src/browser.ts @@ -7,7 +7,7 @@ */ import {CommonModule, PlatformLocation} from '@angular/common'; -import {ApplicationModule, BaseException, ClassProvider, ExceptionHandler, ExistingProvider, FactoryProvider, NgModule, Optional, PLATFORM_INITIALIZER, PlatformRef, Provider, RootRenderer, Sanitizer, SkipSelf, Testability, TypeProvider, ValueProvider, createPlatformFactory, platformCore} from '@angular/core'; +import {ApplicationModule, ClassProvider, ErrorHandler, ExistingProvider, FactoryProvider, NgModule, Optional, PLATFORM_INITIALIZER, PlatformRef, Provider, RootRenderer, Sanitizer, SkipSelf, Testability, TypeProvider, ValueProvider, createPlatformFactory, platformCore} from '@angular/core'; import {wtfInit} from '../core_private'; import {AnimationDriver} from '../src/dom/animation_driver'; @@ -55,8 +55,8 @@ export function initDomAdapter() { BrowserGetTestability.init(); } -export function _exceptionHandler(): ExceptionHandler { - return new ExceptionHandler(getDOM()); +export function errorHandler(): ErrorHandler { + return new ErrorHandler(); } export function _document(): any { @@ -77,8 +77,7 @@ export function _resolveDefaultAnimationDriver(): AnimationDriver { */ @NgModule({ providers: [ - BROWSER_SANITIZATION_PROVIDERS, - {provide: ExceptionHandler, useFactory: _exceptionHandler, deps: []}, + BROWSER_SANITIZATION_PROVIDERS, {provide: ErrorHandler, useFactory: errorHandler, deps: []}, {provide: DOCUMENT, useFactory: _document, deps: []}, {provide: EVENT_MANAGER_PLUGINS, useClass: DomEventsPlugin, multi: true}, {provide: EVENT_MANAGER_PLUGINS, useClass: KeyEventsPlugin, multi: true}, @@ -95,7 +94,7 @@ export function _resolveDefaultAnimationDriver(): AnimationDriver { export class BrowserModule { constructor(@Optional() @SkipSelf() parentModule: BrowserModule) { if (parentModule) { - throw new BaseException( + throw new Error( `BrowserModule has already been loaded. If you need access to common directives such as NgIf and NgFor from a lazy loaded module, import CommonModule instead.`); } } diff --git a/modules/@angular/platform-browser/src/dom/dom_renderer.ts b/modules/@angular/platform-browser/src/dom/dom_renderer.ts index 3e8331d729..cdfe43cb56 100644 --- a/modules/@angular/platform-browser/src/dom/dom_renderer.ts +++ b/modules/@angular/platform-browser/src/dom/dom_renderer.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException, Inject, Injectable, OpaqueToken, RenderComponentType, Renderer, RootRenderer, ViewEncapsulation} from '@angular/core'; +import {Inject, Injectable, OpaqueToken, RenderComponentType, Renderer, RootRenderer, ViewEncapsulation} from '@angular/core'; import {AnimationKeyframe, AnimationPlayer, AnimationStyles, RenderDebugInfo} from '../../core_private'; import {StringMapWrapper} from '../facade/collection'; @@ -79,7 +79,7 @@ export class DomRenderer implements Renderer { if (isString(selectorOrNode)) { el = getDOM().querySelector(this._rootRenderer.document, selectorOrNode); if (isBlank(el)) { - throw new BaseException(`The selector "${selectorOrNode}" did not match any elements`); + throw new Error(`The selector "${selectorOrNode}" did not match any elements`); } } else { el = selectorOrNode; diff --git a/modules/@angular/platform-browser/src/dom/events/event_manager.ts b/modules/@angular/platform-browser/src/dom/events/event_manager.ts index 155deca036..71fe713564 100644 --- a/modules/@angular/platform-browser/src/dom/events/event_manager.ts +++ b/modules/@angular/platform-browser/src/dom/events/event_manager.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException, Inject, Injectable, NgZone, OpaqueToken} from '@angular/core'; +import {Inject, Injectable, NgZone, OpaqueToken} from '@angular/core'; import {ListWrapper} from '../../facade/collection'; @@ -50,7 +50,7 @@ export class EventManager { return plugin; } } - throw new BaseException(`No event manager plugin found for event ${eventName}`); + throw new Error(`No event manager plugin found for event ${eventName}`); } } diff --git a/modules/@angular/platform-browser/src/dom/events/hammer_gestures.ts b/modules/@angular/platform-browser/src/dom/events/hammer_gestures.ts index d4091e50f8..90b83523f9 100644 --- a/modules/@angular/platform-browser/src/dom/events/hammer_gestures.ts +++ b/modules/@angular/platform-browser/src/dom/events/hammer_gestures.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException, Inject, Injectable, OpaqueToken} from '@angular/core'; +import {Inject, Injectable, OpaqueToken} from '@angular/core'; import {isPresent} from '../../facade/lang'; @@ -56,7 +56,7 @@ export class HammerGesturesPlugin extends HammerGesturesPluginCommon { if (!super.supports(eventName) && !this.isCustomEvent(eventName)) return false; if (!isPresent((window as any /** TODO #???? */)['Hammer'])) { - throw new BaseException(`Hammer.js is not loaded, can not bind ${eventName} event`); + throw new Error(`Hammer.js is not loaded, can not bind ${eventName} event`); } return true; diff --git a/modules/@angular/platform-browser/src/dom/web_animations_driver.ts b/modules/@angular/platform-browser/src/dom/web_animations_driver.ts index 22cdbce444..db13b8ec4d 100644 --- a/modules/@angular/platform-browser/src/dom/web_animations_driver.ts +++ b/modules/@angular/platform-browser/src/dom/web_animations_driver.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {AUTO_STYLE, BaseException} from '@angular/core'; +import {AUTO_STYLE} from '@angular/core'; import {AnimationKeyframe, AnimationPlayer, AnimationStyles, NoOpAnimationPlayer} from '../../core_private'; import {StringMapWrapper} from '../facade/collection'; @@ -86,8 +86,7 @@ function _resolveStyleUnit( if (isNumber(val)) { unit = 'px'; } else if (_findDimensionalSuffix(val.toString()).length == 0) { - throw new BaseException( - 'Please provide a CSS unit value for ' + userProvidedProp + ':' + val); + throw new Error('Please provide a CSS unit value for ' + userProvidedProp + ':' + val); } } return unit; diff --git a/modules/@angular/platform-browser/src/web_workers/shared/post_message_bus.ts b/modules/@angular/platform-browser/src/web_workers/shared/post_message_bus.ts index f3724d857b..8f09547e4c 100644 --- a/modules/@angular/platform-browser/src/web_workers/shared/post_message_bus.ts +++ b/modules/@angular/platform-browser/src/web_workers/shared/post_message_bus.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException, Injectable, NgZone} from '@angular/core'; +import {Injectable, NgZone} from '@angular/core'; import {EventEmitter} from '../../facade/async'; import {StringMapWrapper} from '../../facade/collection'; @@ -35,7 +35,7 @@ export class PostMessageBusSink implements MessageBusSink { initChannel(channel: string, runInZone: boolean = true): void { if (StringMapWrapper.contains(this._channels, channel)) { - throw new BaseException(`${channel} has already been initialized`); + throw new Error(`${channel} has already been initialized`); } var emitter = new EventEmitter(false); @@ -55,7 +55,7 @@ export class PostMessageBusSink implements MessageBusSink { if (StringMapWrapper.contains(this._channels, channel)) { return this._channels[channel].emitter; } else { - throw new BaseException(`${channel} is not set up. Did you forget to call initChannel?`); + throw new Error(`${channel} is not set up. Did you forget to call initChannel?`); } } @@ -87,7 +87,7 @@ export class PostMessageBusSource implements MessageBusSource { initChannel(channel: string, runInZone: boolean = true) { if (StringMapWrapper.contains(this._channels, channel)) { - throw new BaseException(`${channel} has already been initialized`); + throw new Error(`${channel} has already been initialized`); } var emitter = new EventEmitter(false); @@ -99,7 +99,7 @@ export class PostMessageBusSource implements MessageBusSource { if (StringMapWrapper.contains(this._channels, channel)) { return this._channels[channel].emitter; } else { - throw new BaseException(`${channel} is not set up. Did you forget to call initChannel?`); + throw new Error(`${channel} is not set up. Did you forget to call initChannel?`); } } diff --git a/modules/@angular/platform-browser/src/web_workers/shared/serializer.ts b/modules/@angular/platform-browser/src/web_workers/shared/serializer.ts index 1382d1bdb5..9fd0f72882 100644 --- a/modules/@angular/platform-browser/src/web_workers/shared/serializer.ts +++ b/modules/@angular/platform-browser/src/web_workers/shared/serializer.ts @@ -10,7 +10,6 @@ import {Injectable, RenderComponentType, Type, ViewEncapsulation} from '@angular import {VIEW_ENCAPSULATION_VALUES} from '../../../core_private'; import {Map, MapWrapper, StringMapWrapper} from '../../facade/collection'; -import {BaseException} from '../../facade/exceptions'; import {isArray, isPresent, serializeEnum} from '../../facade/lang'; import {RenderStore} from './render_store'; import {LocationType} from './serialized_types'; @@ -47,7 +46,7 @@ export class Serializer { } else if (type === LocationType) { return this._serializeLocation(obj); } else { - throw new BaseException('No serializer for ' + type.toString()); + throw new Error('No serializer for ' + type.toString()); } } @@ -73,7 +72,7 @@ export class Serializer { } else if (type === LocationType) { return this._deserializeLocation(map); } else { - throw new BaseException('No deserializer for ' + type.toString()); + throw new Error('No deserializer for ' + type.toString()); } } diff --git a/modules/@angular/platform-browser/src/web_workers/ui/event_dispatcher.ts b/modules/@angular/platform-browser/src/web_workers/ui/event_dispatcher.ts index 79f0eebad4..2f2d9ee106 100644 --- a/modules/@angular/platform-browser/src/web_workers/ui/event_dispatcher.ts +++ b/modules/@angular/platform-browser/src/web_workers/ui/event_dispatcher.ts @@ -6,7 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException} from '@angular/core'; import {EventEmitter} from '../../facade/async'; import {RenderStoreObject, Serializer} from '../shared/serializer'; @@ -97,7 +96,7 @@ export class EventDispatcher { serializedEvent = serializeTransitionEvent(event); break; default: - throw new BaseException(eventName + ' not supported on WebWorkers'); + throw new Error(eventName + ' not supported on WebWorkers'); } this._sink.emit({ 'element': this._serializer.serialize(element, RenderStoreObject), diff --git a/modules/@angular/platform-browser/src/web_workers/worker/platform_location.ts b/modules/@angular/platform-browser/src/web_workers/worker/platform_location.ts index 204b026c37..a6d91c85ea 100644 --- a/modules/@angular/platform-browser/src/web_workers/worker/platform_location.ts +++ b/modules/@angular/platform-browser/src/web_workers/worker/platform_location.ts @@ -7,7 +7,7 @@ */ import {LocationChangeListener, PlatformLocation} from '@angular/common'; -import {BaseException, Injectable} from '@angular/core'; +import {Injectable} from '@angular/core'; import {EventEmitter} from '../../facade/async'; import {StringMapWrapper} from '../../facade/collection'; @@ -67,11 +67,11 @@ export class WebWorkerPlatformLocation extends PlatformLocation { this._location = val; return true; }, - (err): boolean => { throw new BaseException(err); }); + (err): boolean => { throw new Error(err); }); } getBaseHrefFromDOM(): string { - throw new BaseException( + throw new Error( 'Attempt to get base href from DOM from WebWorker. You must either provide a value for the APP_BASE_HREF token through DI or use the hash location strategy.'); } @@ -105,7 +105,7 @@ export class WebWorkerPlatformLocation extends PlatformLocation { set pathname(newPath: string) { if (this._location === null) { - throw new BaseException('Attempt to set pathname before value is obtained from UI'); + throw new Error('Attempt to set pathname before value is obtained from UI'); } this._location.pathname = newPath; diff --git a/modules/@angular/platform-browser/src/worker_app.ts b/modules/@angular/platform-browser/src/worker_app.ts index e8291f309a..06116e0c24 100644 --- a/modules/@angular/platform-browser/src/worker_app.ts +++ b/modules/@angular/platform-browser/src/worker_app.ts @@ -7,8 +7,7 @@ */ import {CommonModule} from '@angular/common'; -import {APP_INITIALIZER, ApplicationModule, ClassProvider, ExceptionHandler, ExistingProvider, FactoryProvider, NgModule, NgZone, PlatformRef, RootRenderer, TypeProvider, ValueProvider, createPlatformFactory, platformCore} from '@angular/core'; - +import {APP_INITIALIZER, ApplicationModule, ClassProvider, ErrorHandler, ExistingProvider, FactoryProvider, NgModule, NgZone, OpaqueToken, PlatformRef, ReflectiveInjector, RootRenderer, TypeProvider, ValueProvider, assertPlatform, createPlatform, createPlatformFactory, getPlatform, platformCore} from '@angular/core'; import {BROWSER_SANITIZATION_PROVIDERS} from './browser'; import {print} from './facade/lang'; import {ON_WEB_WORKER} from './web_workers/shared/api'; @@ -22,18 +21,6 @@ import {WebWorkerRootRenderer} from './web_workers/worker/renderer'; import {WorkerDomAdapter} from './web_workers/worker/worker_adapter'; -/** - * Logger for web workers. - * - * @experimental - */ -export class PrintLogger { - log = print; - logError = print; - logGroup = print; - logGroupEnd() {} -} - /** * @experimental */ @@ -44,8 +31,8 @@ export const platformWorkerApp = createPlatformFactory(platformCore, 'workerApp' * * @experimental */ -export function exceptionHandler(): ExceptionHandler { - return new ExceptionHandler(new PrintLogger()); +export function errorHandler(): ErrorHandler { + return new ErrorHandler(); } // TODO(jteplitz602) remove this and compile with lib.webworker.d.ts (#3492) @@ -89,7 +76,7 @@ export function setupWebWorker(): void { {provide: ServiceMessageBrokerFactory, useClass: ServiceMessageBrokerFactory_}, WebWorkerRootRenderer, {provide: RootRenderer, useExisting: WebWorkerRootRenderer}, {provide: ON_WEB_WORKER, useValue: true}, RenderStore, - {provide: ExceptionHandler, useFactory: exceptionHandler, deps: []}, + {provide: ErrorHandler, useFactory: errorHandler, deps: []}, {provide: MessageBus, useFactory: createMessageBus, deps: [NgZone]}, {provide: APP_INITIALIZER, useValue: setupWebWorker, multi: true} ], diff --git a/modules/@angular/platform-browser/src/worker_render.ts b/modules/@angular/platform-browser/src/worker_render.ts index a4cb724bf3..0ae03a8343 100644 --- a/modules/@angular/platform-browser/src/worker_render.ts +++ b/modules/@angular/platform-browser/src/worker_render.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException, ClassProvider, ExceptionHandler, ExistingProvider, FactoryProvider, Injectable, Injector, NgZone, OpaqueToken, PLATFORM_INITIALIZER, PlatformRef, Provider, RootRenderer, Testability, TypeProvider, ValueProvider, createPlatformFactory, isDevMode, platformCore} from '@angular/core'; +import {ClassProvider, ErrorHandler, ExistingProvider, FactoryProvider, Injectable, Injector, NgZone, OpaqueToken, PLATFORM_INITIALIZER, PlatformRef, Provider, RootRenderer, Testability, TypeProvider, ValueProvider, createPlatformFactory, isDevMode, platformCore} from '@angular/core'; import {wtfInit} from '../core_private'; @@ -74,7 +74,7 @@ export const _WORKER_UI_PLATFORM_PROVIDERS: Provider[] = [ MessageBasedRenderer, {provide: WORKER_UI_STARTABLE_MESSAGING_SERVICE, useExisting: MessageBasedRenderer, multi: true}, BROWSER_SANITIZATION_PROVIDERS, - {provide: ExceptionHandler, useFactory: _exceptionHandler, deps: []}, + {provide: ErrorHandler, useFactory: _exceptionHandler, deps: []}, {provide: DOCUMENT, useFactory: _document, deps: []}, // TODO(jteplitz602): Investigate if we definitely need EVENT_MANAGER on the render thread // #5298 @@ -127,7 +127,7 @@ function initWebWorkerRenderPlatform(injector: Injector): () => void { try { scriptUri = injector.get(WORKER_SCRIPT); } catch (e) { - throw new BaseException( + throw new Error( 'You must provide your WebWorker\'s initialization script with the WORKER_SCRIPT token'); } @@ -144,8 +144,8 @@ function initWebWorkerRenderPlatform(injector: Injector): () => void { export const platformWorkerUi = createPlatformFactory(platformCore, 'workerUi', _WORKER_UI_PLATFORM_PROVIDERS); -function _exceptionHandler(): ExceptionHandler { - return new ExceptionHandler(getDOM()); +function _exceptionHandler(): ErrorHandler { + return new ErrorHandler(); } function _document(): any { diff --git a/modules/@angular/platform-browser/test/browser/bootstrap_spec.ts b/modules/@angular/platform-browser/test/browser/bootstrap_spec.ts index ca6b994d32..658ce665e3 100644 --- a/modules/@angular/platform-browser/test/browser/bootstrap_spec.ts +++ b/modules/@angular/platform-browser/test/browser/bootstrap_spec.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {APP_INITIALIZER, CUSTOM_ELEMENTS_SCHEMA, Compiler, Component, Directive, ExceptionHandler, Inject, Input, NgModule, OnDestroy, PLATFORM_INITIALIZER, Pipe, Provider, createPlatformFactory} from '@angular/core'; +import {APP_INITIALIZER, CUSTOM_ELEMENTS_SCHEMA, Compiler, Component, Directive, ErrorHandler, Inject, Input, NgModule, OnDestroy, PLATFORM_INITIALIZER, Pipe, Provider, createPlatformFactory} from '@angular/core'; import {ApplicationRef, destroyPlatform} from '@angular/core/src/application_ref'; import {Console} from '@angular/core/src/console'; import {ComponentRef} from '@angular/core/src/linker/component_factory'; @@ -94,12 +94,9 @@ class HelloCmpUsingPlatformDirectiveAndPipe { class HelloCmpUsingCustomElement { } -class _ArrayLogger { +class MockConsole { res: any[] = []; - log(s: any): void { this.res.push(s); } - logError(s: any): void { this.res.push(s); } - logGroup(s: any): void { this.res.push(s); } - logGroupEnd(){}; + error(s: any): void { this.res.push(s); } } @@ -160,10 +157,11 @@ export function main() { it('should throw if no element is found', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - var logger = new _ArrayLogger(); - var exceptionHandler = new ExceptionHandler(logger, false); + var logger = new MockConsole(); + var errorHandler = new ErrorHandler(false); + errorHandler._console = logger as any; bootstrap(HelloRootCmp, [ - {provide: ExceptionHandler, useValue: exceptionHandler} + {provide: ErrorHandler, useValue: errorHandler} ]).then(null, (reason) => { expect(reason.message).toContain('The selector "hello-app" did not match any elements'); async.done(); @@ -174,11 +172,12 @@ export function main() { if (getDOM().supportsDOMEvents()) { it('should forward the error to promise when bootstrap fails', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - var logger = new _ArrayLogger(); - var exceptionHandler = new ExceptionHandler(logger, false); + var logger = new MockConsole(); + var errorHandler = new ErrorHandler(false); + errorHandler._console = logger as any; var refPromise = - bootstrap(HelloRootCmp, [{provide: ExceptionHandler, useValue: exceptionHandler}]); + bootstrap(HelloRootCmp, [{provide: ErrorHandler, useValue: errorHandler}]); refPromise.then(null, (reason: any) => { expect(reason.message) .toContain('The selector "hello-app" did not match any elements'); @@ -188,11 +187,12 @@ export function main() { it('should invoke the default exception handler when bootstrap fails', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - var logger = new _ArrayLogger(); - var exceptionHandler = new ExceptionHandler(logger, false); + var logger = new MockConsole(); + var errorHandler = new ErrorHandler(false); + errorHandler._console = logger as any; var refPromise = - bootstrap(HelloRootCmp, [{provide: ExceptionHandler, useValue: exceptionHandler}]); + bootstrap(HelloRootCmp, [{provide: ErrorHandler, useValue: errorHandler}]); refPromise.then(null, (reason) => { expect(logger.res.join('')) .toContain('The selector "hello-app" did not match any elements'); diff --git a/modules/@angular/platform-browser/test/web_workers/shared/web_worker_test_util.ts b/modules/@angular/platform-browser/test/web_workers/shared/web_worker_test_util.ts index 0e2ebb0cb0..9ad23e3287 100644 --- a/modules/@angular/platform-browser/test/web_workers/shared/web_worker_test_util.ts +++ b/modules/@angular/platform-browser/test/web_workers/shared/web_worker_test_util.ts @@ -11,7 +11,6 @@ import {NgZone} from '@angular/core/src/zone/ng_zone'; import {ClientMessageBroker, ClientMessageBrokerFactory_, UiArguments} from '@angular/platform-browser/src/web_workers/shared/client_message_broker'; import {MessageBus, MessageBusSink, MessageBusSource} from '@angular/platform-browser/src/web_workers/shared/message_bus'; import {ListWrapper, StringMapWrapper} from '../../../src/facade/collection'; -import {BaseException} from '../../../src/facade/exceptions'; import {isPresent} from '../../../src/facade/lang'; import {SpyMessageBroker} from '../worker/spies'; @@ -89,7 +88,7 @@ export class MockMessageBusSource implements MessageBusSource { from(channel: string): MockEventEmitter { if (!StringMapWrapper.contains(this._channels, channel)) { - throw new BaseException(`${channel} is not set up. Did you forget to call initChannel?`); + throw new Error(`${channel} is not set up. Did you forget to call initChannel?`); } return this._channels[channel]; } diff --git a/modules/@angular/platform-browser/testing/benchmark_util.ts b/modules/@angular/platform-browser/testing/benchmark_util.ts index d494413889..e2ae77cd06 100644 --- a/modules/@angular/platform-browser/testing/benchmark_util.ts +++ b/modules/@angular/platform-browser/testing/benchmark_util.ts @@ -6,7 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException} from '@angular/core'; import {BrowserDomAdapter} from '../src/browser/browser_adapter'; import {document, window} from '../src/facade/browser'; @@ -33,7 +32,7 @@ export function getStringParameter(name: string) { } if (isBlank(value)) { - throw new BaseException(`Could not find and input field with name ${name}`); + throw new Error(`Could not find and input field with name ${name}`); } return value; diff --git a/modules/@angular/platform-server/src/parse5_adapter.ts b/modules/@angular/platform-server/src/parse5_adapter.ts index 209de2e274..ad3f46fd69 100644 --- a/modules/@angular/platform-server/src/parse5_adapter.ts +++ b/modules/@angular/platform-server/src/parse5_adapter.ts @@ -11,7 +11,6 @@ var parse5 = require('parse5/index'); import {ListWrapper, StringMapWrapper} from '../src/facade/collection'; import {DomAdapter, setRootDomAdapter} from '../platform_browser_private'; import {isPresent, isBlank, global, setValueOnPath, DateWrapper} from '../src/facade/lang'; -import {BaseException} from '../src/facade/exceptions'; import {SelectorMatcher, CssSelector} from '../compiler_private'; import {Type} from '@angular/core'; import {ResourceLoader} from '@angular/compiler'; @@ -31,7 +30,7 @@ var defDoc: any /** TODO #9100 */ = null; var mapProps = ['attribs', 'x-attribsNamespace', 'x-attribsPrefix']; function _notImplemented(methodName: any /** TODO #9100 */) { - return new BaseException('This method is not implemented in Parse5DomAdapter: ' + methodName); + return new Error('This method is not implemented in Parse5DomAdapter: ' + methodName); } /* tslint:disable:requireParameterType */ diff --git a/modules/@angular/router/src/directives/router_outlet.ts b/modules/@angular/router/src/directives/router_outlet.ts index a87de10a53..8f589c5e88 100644 --- a/modules/@angular/router/src/directives/router_outlet.ts +++ b/modules/@angular/router/src/directives/router_outlet.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {Attribute, ComponentFactory, ComponentFactoryResolver, ComponentRef, Directive, EventEmitter, Injector, NoComponentFactoryError, OnDestroy, Output, ReflectiveInjector, ResolvedReflectiveProvider, ViewContainerRef} from '@angular/core'; +import {Attribute, ComponentFactory, ComponentFactoryResolver, ComponentRef, Directive, EventEmitter, Injector, OnDestroy, Output, ReflectiveInjector, ResolvedReflectiveProvider, ViewContainerRef} from '@angular/core'; import {RouterOutletMap} from '../router_outlet_map'; import {ActivatedRoute} from '../router_state'; diff --git a/modules/@angular/router/src/router_module.ts b/modules/@angular/router/src/router_module.ts index 4e41fd4729..2bffc26636 100644 --- a/modules/@angular/router/src/router_module.ts +++ b/modules/@angular/router/src/router_module.ts @@ -7,7 +7,7 @@ */ import {APP_BASE_HREF, HashLocationStrategy, Location, LocationStrategy, PathLocationStrategy, PlatformLocation} from '@angular/common'; -import {ANALYZE_FOR_ENTRY_COMPONENTS, APP_BOOTSTRAP_LISTENER, ApplicationRef, BaseException, Compiler, Inject, Injector, ModuleWithProviders, NgModule, NgModuleFactoryLoader, OpaqueToken, Optional, Provider, SkipSelf, SystemJsNgModuleLoader} from '@angular/core'; +import {ANALYZE_FOR_ENTRY_COMPONENTS, APP_BOOTSTRAP_LISTENER, ApplicationRef, Compiler, Inject, Injector, ModuleWithProviders, NgModule, NgModuleFactoryLoader, OpaqueToken, Optional, Provider, SkipSelf, SystemJsNgModuleLoader} from '@angular/core'; import {Route, Routes} from './config'; import {RouterLink, RouterLinkWithHref} from './directives/router_link'; @@ -119,7 +119,7 @@ export function provideLocationStrategy( export function provideForRootGuard(router: Router): any { if (router) { - throw new BaseException( + throw new Error( `RouterModule.forRoot() called twice. Lazy loaded modules should use RouterModule.forChild() instead.`); } return 'guarded'; diff --git a/modules/@angular/router/src/shared.ts b/modules/@angular/router/src/shared.ts index 06e7526a89..2b45aceb2e 100644 --- a/modules/@angular/router/src/shared.ts +++ b/modules/@angular/router/src/shared.ts @@ -30,4 +30,4 @@ export class NavigationCancelingError extends Error { this.stack = (new Error(message)).stack; } toString(): string { return this.message; } -} \ No newline at end of file +} diff --git a/modules/@angular/upgrade/src/upgrade_adapter.ts b/modules/@angular/upgrade/src/upgrade_adapter.ts index e8caeab8af..14566492b2 100644 --- a/modules/@angular/upgrade/src/upgrade_adapter.ts +++ b/modules/@angular/upgrade/src/upgrade_adapter.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException, Compiler, ComponentFactory, ComponentFactoryResolver, Injector, NgModule, NgModuleRef, NgZone, Provider, Testability, Type} from '@angular/core'; +import {Compiler, ComponentFactory, ComponentFactoryResolver, Injector, NgModule, NgModuleRef, NgZone, Provider, Testability, Type} from '@angular/core'; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import * as angular from './angular_js'; @@ -116,7 +116,7 @@ export class UpgradeAdapter { constructor(private ng2AppModule: Type) { if (!ng2AppModule) { - throw new BaseException( + throw new Error( 'UpgradeAdapter cannot be instantiated without an NgModule of the Angular 2 app.'); } } diff --git a/modules/angular1_router/lib/facades.es5 b/modules/angular1_router/lib/facades.es5 index b98a78aa13..5e15c0f871 100644 --- a/modules/angular1_router/lib/facades.es5 +++ b/modules/angular1_router/lib/facades.es5 @@ -286,8 +286,6 @@ var StringWrapper = { // I think it's too heavy to ask 1.x users to bring in Rx for the router... function EventEmitter() {} -var BaseException = Error; - var ObservableWrapper = { callNext: function(ob, val) { ob.fn(val); diff --git a/modules/angular1_router/src/module_template.js b/modules/angular1_router/src/module_template.js index 9862f9e358..f648cbce42 100644 --- a/modules/angular1_router/src/module_template.js +++ b/modules/angular1_router/src/module_template.js @@ -52,11 +52,11 @@ function routerFactory($q, $location, $browser, $rootScope, $injector, $routerRo if ($injector.has(serviceName)) { var definitions = $injector.get(serviceName); if (definitions.length > 1) { - throw new BaseException('too many directives named "' + name + '"'); + throw new Error('too many directives named "' + name + '"'); } return definitions[0].controller; } else { - throw new BaseException('directive "' + name + '" is not registered'); + throw new Error('directive "' + name + '" is not registered'); } } diff --git a/modules/benchpress/src/metric.ts b/modules/benchpress/src/metric.ts index 70463e6443..db15792495 100644 --- a/modules/benchpress/src/metric.ts +++ b/modules/benchpress/src/metric.ts @@ -6,7 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException, WrappedException} from '@angular/facade/src/exceptions'; /** * A metric is measures values @@ -19,18 +18,18 @@ export abstract class Metric { /** * Starts measuring */ - beginMeasure(): Promise { throw new BaseException('NYI'); } + beginMeasure(): Promise { throw new Error('NYI'); } /** * Ends measuring and reports the data * since the begin call. * @param restart: Whether to restart right after this. */ - endMeasure(restart: boolean): Promise<{[key: string]: any}> { throw new BaseException('NYI'); } + endMeasure(restart: boolean): Promise<{[key: string]: any}> { throw new Error('NYI'); } /** * Describes the metrics provided by this metric implementation. * (e.g. units, ...) */ - describe(): {[key: string]: any} { throw new BaseException('NYI'); } + describe(): {[key: string]: any} { throw new Error('NYI'); } } diff --git a/modules/benchpress/src/metric/perflog_metric.ts b/modules/benchpress/src/metric/perflog_metric.ts index acda4e42f1..ad201912e6 100644 --- a/modules/benchpress/src/metric/perflog_metric.ts +++ b/modules/benchpress/src/metric/perflog_metric.ts @@ -8,7 +8,6 @@ import {OpaqueToken} from '@angular/core/src/di'; import {ListWrapper, StringMapWrapper} from '@angular/facade/src/collection'; -import {BaseException, WrappedException} from '@angular/facade/src/exceptions'; import {Math, NumberWrapper, StringWrapper, isBlank, isPresent} from '@angular/facade/src/lang'; import {Options} from '../common_options'; @@ -157,7 +156,7 @@ export class PerflogMetric extends Metric { /** @internal */ private _readUntilEndMark(markName: string, loopCount: number = 0, startEvent = null) { if (loopCount > _MAX_RETRY_COUNT) { - throw new BaseException(`Tried too often to get the ending mark: ${loopCount}`); + throw new Error(`Tried too often to get the ending mark: ${loopCount}`); } return this._driverExtension.readPerfLog().then((events) => { this._addEvents(events); @@ -276,17 +275,17 @@ export class PerflogMetric extends Metric { event['pid'] === markStartEvent['pid']) { if (StringWrapper.equals(ph, 'b') && StringWrapper.equals(name, _MARK_NAME_FRAME_CAPUTRE)) { if (isPresent(frameCaptureStartEvent)) { - throw new BaseException('can capture frames only once per benchmark run'); + throw new Error('can capture frames only once per benchmark run'); } if (!this._captureFrames) { - throw new BaseException( + throw new Error( 'found start event for frame capture, but frame capture was not requested in benchpress'); } frameCaptureStartEvent = event; } else if ( StringWrapper.equals(ph, 'e') && StringWrapper.equals(name, _MARK_NAME_FRAME_CAPUTRE)) { if (isBlank(frameCaptureStartEvent)) { - throw new BaseException('missing start event for frame capture'); + throw new Error('missing start event for frame capture'); } frameCaptureEndEvent = event; } @@ -351,11 +350,10 @@ export class PerflogMetric extends Metric { if (isPresent(markEndEvent) && isPresent(frameCaptureStartEvent) && isBlank(frameCaptureEndEvent)) { - throw new BaseException('missing end event for frame capture'); + throw new Error('missing end event for frame capture'); } if (this._captureFrames && isBlank(frameCaptureStartEvent)) { - throw new BaseException( - 'frame capture requested in benchpress, but no start event was found'); + throw new Error('frame capture requested in benchpress, but no start event was found'); } if (frameTimes.length > 0) { this._addFrameMetrics(result, frameTimes); diff --git a/modules/benchpress/src/reporter.ts b/modules/benchpress/src/reporter.ts index c57ade298e..4fcca55c5d 100644 --- a/modules/benchpress/src/reporter.ts +++ b/modules/benchpress/src/reporter.ts @@ -6,7 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException, WrappedException} from '@angular/facade/src/exceptions'; import {MeasureValues} from './measure_values'; /** @@ -17,9 +16,9 @@ export abstract class Reporter { return [{provide: Reporter, useFactory: (delegate) => delegate, deps: [delegateToken]}]; } - reportMeasureValues(values: MeasureValues): Promise { throw new BaseException('NYI'); } + reportMeasureValues(values: MeasureValues): Promise { throw new Error('NYI'); } reportSample(completeSample: MeasureValues[], validSample: MeasureValues[]): Promise { - throw new BaseException('NYI'); + throw new Error('NYI'); } } diff --git a/modules/benchpress/src/validator.ts b/modules/benchpress/src/validator.ts index 12db900a8d..71af984b72 100644 --- a/modules/benchpress/src/validator.ts +++ b/modules/benchpress/src/validator.ts @@ -6,8 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException, WrappedException} from '@angular/facade/src/exceptions'; - import {MeasureValues} from './measure_values'; /** @@ -23,11 +21,11 @@ export abstract class Validator { /** * Calculates a valid sample out of the complete sample */ - validate(completeSample: MeasureValues[]): MeasureValues[] { throw new BaseException('NYI'); } + validate(completeSample: MeasureValues[]): MeasureValues[] { throw new Error('NYI'); } /** * Returns a Map that describes the properties of the validator * (e.g. sample size, ...) */ - describe(): {[key: string]: any} { throw new BaseException('NYI'); } + describe(): {[key: string]: any} { throw new Error('NYI'); } } diff --git a/modules/benchpress/src/web_driver_adapter.ts b/modules/benchpress/src/web_driver_adapter.ts index cdc7b901fe..ab65c8af31 100644 --- a/modules/benchpress/src/web_driver_adapter.ts +++ b/modules/benchpress/src/web_driver_adapter.ts @@ -6,8 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ -import {Map} from '@angular/facade/src/collection'; -import {BaseException, WrappedException} from '@angular/facade/src/exceptions'; /** @@ -20,9 +18,9 @@ export abstract class WebDriverAdapter { return [{provide: WebDriverAdapter, useFactory: (delegate) => delegate, deps: [delegateToken]}]; } - waitFor(callback: Function): Promise { throw new BaseException('NYI'); } - executeScript(script: string): Promise { throw new BaseException('NYI'); } - executeAsyncScript(script: string): Promise { throw new BaseException('NYI'); } - capabilities(): Promise> { throw new BaseException('NYI'); } - logs(type: string): Promise { throw new BaseException('NYI'); } + waitFor(callback: Function): Promise { throw new Error('NYI'); } + executeScript(script: string): Promise { throw new Error('NYI'); } + executeAsyncScript(script: string): Promise { throw new Error('NYI'); } + capabilities(): Promise> { throw new Error('NYI'); } + logs(type: string): Promise { throw new Error('NYI'); } } diff --git a/modules/benchpress/src/web_driver_extension.ts b/modules/benchpress/src/web_driver_extension.ts index 60ad413e76..9151ea4b1c 100644 --- a/modules/benchpress/src/web_driver_extension.ts +++ b/modules/benchpress/src/web_driver_extension.ts @@ -7,7 +7,6 @@ */ import {Injector, OpaqueToken} from '@angular/core/src/di'; -import {BaseException, WrappedException} from '@angular/facade/src/exceptions'; import {isBlank, isPresent} from '@angular/facade/src/lang'; import {Options} from './common_options'; @@ -36,7 +35,7 @@ export abstract class WebDriverExtension { } }); if (isBlank(delegate)) { - throw new BaseException('Could not find a delegate for given capabilities!'); + throw new Error('Could not find a delegate for given capabilities!'); } return delegate; }, @@ -46,11 +45,11 @@ export abstract class WebDriverExtension { return res; } - gc(): Promise { throw new BaseException('NYI'); } + gc(): Promise { throw new Error('NYI'); } - timeBegin(name: string): Promise { throw new BaseException('NYI'); } + timeBegin(name: string): Promise { throw new Error('NYI'); } - timeEnd(name: string, restartName: string): Promise { throw new BaseException('NYI'); } + timeEnd(name: string, restartName: string): Promise { throw new Error('NYI'); } /** * Format: @@ -65,9 +64,9 @@ export abstract class WebDriverExtension { * Based on [Chrome Trace Event *Format](https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/edit) **/ - readPerfLog(): Promise { throw new BaseException('NYI'); } + readPerfLog(): Promise { throw new Error('NYI'); } - perfLogFeatures(): PerfLogFeatures { throw new BaseException('NYI'); } + perfLogFeatures(): PerfLogFeatures { throw new Error('NYI'); } supports(capabilities: {[key: string]: any}): boolean { return true; } } diff --git a/modules/benchpress/src/webdriver/chrome_driver_extension.ts b/modules/benchpress/src/webdriver/chrome_driver_extension.ts index 2ac31344aa..18468746a9 100644 --- a/modules/benchpress/src/webdriver/chrome_driver_extension.ts +++ b/modules/benchpress/src/webdriver/chrome_driver_extension.ts @@ -7,7 +7,6 @@ */ import {ListWrapper, StringMapWrapper} from '@angular/facade/src/collection'; -import {BaseException, WrappedException} from '@angular/facade/src/exceptions'; import {Json, NumberWrapper, StringWrapper, isBlank, isPresent} from '@angular/facade/src/lang'; import {Options} from '../common_options'; @@ -77,7 +76,7 @@ export class ChromeDriverExtension extends WebDriverExtension { events.push(message['params']); } if (StringWrapper.equals(message['method'], 'Tracing.bufferUsage')) { - throw new BaseException('The DevTools trace buffer filled during the test!'); + throw new Error('The DevTools trace buffer filled during the test!'); } }); return this._convertPerfRecordsToEvents(events); @@ -108,7 +107,7 @@ export class ChromeDriverExtension extends WebDriverExtension { // always available if something is rendered var frameCount = event['args']['data']['frame_count']; if (frameCount > 1) { - throw new BaseException('multi-frame render stats not supported'); + throw new Error('multi-frame render stats not supported'); } if (frameCount == 1) { normalizedEvents.push(normalizeEvent(event, {'name': 'frame'})); diff --git a/modules/benchpress/src/webdriver/ios_driver_extension.ts b/modules/benchpress/src/webdriver/ios_driver_extension.ts index 90e33d42e6..13aa3378c5 100644 --- a/modules/benchpress/src/webdriver/ios_driver_extension.ts +++ b/modules/benchpress/src/webdriver/ios_driver_extension.ts @@ -6,7 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ -import {BaseException, WrappedException} from '@angular/facade/src/exceptions'; import {Json, StringWrapper, isBlank, isPresent} from '@angular/facade/src/lang'; import {WebDriverAdapter} from '../web_driver_adapter'; @@ -18,7 +17,7 @@ export class IOsDriverExtension extends WebDriverExtension { constructor(private _driver: WebDriverAdapter) { super(); } - gc(): Promise { throw new BaseException('Force GC is not supported on iOS'); } + gc(): Promise { throw new Error('Force GC is not supported on iOS'); } timeBegin(name: string): Promise { return this._driver.executeScript(`console.time('${name}');`); diff --git a/modules/playground/e2e_test/sourcemap/sourcemap_spec.ts b/modules/playground/e2e_test/sourcemap/sourcemap_spec.ts index 6ab8ac59bb..8e36a24635 100644 --- a/modules/playground/e2e_test/sourcemap/sourcemap_spec.ts +++ b/modules/playground/e2e_test/sourcemap/sourcemap_spec.ts @@ -52,7 +52,7 @@ describe('sourcemaps', function() { encoding: 'UTF-8' }).split('\n'); expect(sourceCodeLines[originalPosition.line - 1]) - .toMatch(/throw new BaseException\(\'Sourcemap test\'\)/); + .toMatch(/throw new Error\(\'Sourcemap test\'\)/); }); }); }); diff --git a/modules/playground/src/sourcemap/index.ts b/modules/playground/src/sourcemap/index.ts index 994cf84f02..497f88e2d9 100644 --- a/modules/playground/src/sourcemap/index.ts +++ b/modules/playground/src/sourcemap/index.ts @@ -7,7 +7,6 @@ */ import {Component, NgModule} from '@angular/core'; -import {BaseException} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; @@ -17,7 +16,7 @@ import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; ` }) export class ErrorComponent { - createError(): void { throw new BaseException('Sourcemap test'); } + createError(): void { throw new Error('Sourcemap test'); } } @NgModule({declarations: [ErrorComponent], bootstrap: [ErrorComponent], imports: [BrowserModule]}) diff --git a/tools/public_api_guard/core/index.d.ts b/tools/public_api_guard/core/index.d.ts index 53f3073c03..fd2ed0ca36 100644 --- a/tools/public_api_guard/core/index.d.ts +++ b/tools/public_api_guard/core/index.d.ts @@ -1,10 +1,3 @@ -/** @stable */ -export declare class AbstractProviderError extends BaseException { - context: any; - constructor(injector: ReflectiveInjector, key: ReflectiveKey, constructResolvingMessage: Function); - addKey(injector: ReflectiveInjector, key: ReflectiveKey): void; -} - /** @stable */ export declare abstract class AfterContentChecked { abstract ngAfterContentChecked(): void; @@ -185,14 +178,6 @@ export interface AttributeMetadataFactory { /** @experimental */ export declare const AUTO_STYLE: string; -/** @stable */ -export declare class BaseException extends Error { - message: string; - stack: any; - constructor(message?: string); - toString(): string; -} - /** @stable */ export declare enum ChangeDetectionStrategy { OnPush = 0, @@ -331,12 +316,6 @@ export declare abstract class ComponentRef { abstract onDestroy(callback: Function): void; } -/** @stable */ -export declare class ComponentStillLoadingError extends BaseException { - compType: Type; - constructor(compType: Type); -} - /** @stable */ export declare var ContentChild: ContentChildMetadataFactory; @@ -389,11 +368,6 @@ export declare function createPlatformFactory(parentPlaformFactory: PlatformFact /** @stable */ export declare const CUSTOM_ELEMENTS_SCHEMA: SchemaMetadata; -/** @stable */ -export declare class CyclicDependencyError extends AbstractProviderError { - constructor(injector: ReflectiveInjector, key: ReflectiveKey); -} - /** @experimental */ export declare class DebugElement extends DebugNode { attributes: { @@ -525,6 +499,12 @@ export declare abstract class EmbeddedViewRef extends ViewRef { /** @stable */ export declare function enableProdMode(): void; +/** @stable */ +export declare class ErrorHandler { + constructor(rethrowError?: boolean); + handleError(error: any): void; +} + /** @stable */ export declare class EventEmitter extends Subject { __isAsync: boolean; @@ -533,13 +513,6 @@ export declare class EventEmitter extends Subject { subscribe(generatorOrNext?: any, error?: any, complete?: any): any; } -/** @stable */ -export declare class ExceptionHandler { - constructor(_logger: any, _rethrowException?: boolean); - call(exception: any, stackTrace?: any, reason?: string): void; - static exceptionToString(exception: any, stackTrace?: any, reason?: string): string; -} - /** @stable */ export interface ExistingProvider { multi?: boolean; @@ -547,11 +520,6 @@ export interface ExistingProvider { useExisting: any; } -/** @stable */ -export declare class ExpressionChangedAfterItHasBeenCheckedException extends BaseException { - constructor(oldValue: any, currValue: any, context: any); -} - /** @stable */ export interface FactoryProvider { deps?: any[]; @@ -681,20 +649,6 @@ export interface InputMetadataFactory { new (bindingPropertyName?: string): any; } -/** @stable */ -export declare class InstantiationError extends WrappedException { - causeKey: ReflectiveKey; - context: any; - wrapperMessage: string; - constructor(injector: ReflectiveInjector, originalException: any, originalStack: any, key: ReflectiveKey); - addKey(injector: ReflectiveInjector, key: ReflectiveKey): void; -} - -/** @stable */ -export declare class InvalidProviderError extends BaseException { - constructor(provider: any); -} - /** @experimental */ export declare function isDevMode(): boolean; @@ -850,22 +804,6 @@ export declare class NgZone { /** @experimental */ export declare const NO_ERRORS_SCHEMA: SchemaMetadata; -/** @stable */ -export declare class NoAnnotationError extends BaseException { - constructor(typeOrFunc: Type | Function, params: any[][]); -} - -/** @stable */ -export declare class NoComponentFactoryError extends BaseException { - component: Function; - constructor(component: Function); -} - -/** @stable */ -export declare class NoProviderError extends AbstractProviderError { - constructor(injector: ReflectiveInjector, key: ReflectiveKey); -} - /** @stable */ export declare abstract class OnChanges { abstract ngOnChanges(changes: SimpleChanges): void; @@ -901,11 +839,6 @@ export interface OptionalMetadataFactory { new (): OptionalMetadata; } -/** @stable */ -export declare class OutOfBoundsError extends BaseException { - constructor(index: number); -} - /** @stable */ export declare var Output: OutputMetadataFactory; @@ -1328,18 +1261,6 @@ export declare abstract class ViewRef { abstract onDestroy(callback: Function): any; } -/** @stable */ -export declare class WrappedException extends BaseWrappedException { - context: any; - message: string; - originalException: any; - originalStack: any; - wrapperMessage: string; - wrapperStack: any; - constructor(_wrapperMessage: string, _originalException: any, _originalStack?: any, _context?: any); - toString(): string; -} - /** @stable */ export declare class WrappedValue { wrapped: any;