fix(errors): [2/2] Rename Exception to Error; remove from public API

BREAKING CHANGE:

Exceptions are no longer part of the public API. We don't expect that anyone should be referring to the Exception types.

ExceptionHandler.call(exception: any, stackTrace?: any, reason?: string): void;
change to:
ErrorHandler.handleError(error: any): void;
This commit is contained in:
Misko Hevery 2016-08-25 00:50:16 -07:00 committed by Victor Berchet
parent 86ba072758
commit 7c07bfff97
142 changed files with 565 additions and 774 deletions

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license * 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'; import {getTypeNameForDebugging, isBlank, isPresent} from '../facade/lang';
@ -112,7 +112,7 @@ export class NgFor implements DoCheck, OnChanges {
try { try {
this._differ = this._iterableDiffers.find(value).create(this._cdr, this.ngForTrackBy); this._differ = this._iterableDiffers.find(value).create(this._cdr, this.ngForTrackBy);
} catch (e) { } 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.`); `Cannot find a differ supporting object '${value}' of type '${getTypeNameForDebugging(value)}'. NgFor only supports binding to Iterables such as Arrays.`);
} }
} }

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license * 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'; import {isBlank} from '../facade/lang';
@ -53,7 +53,7 @@ export class PathLocationStrategy extends LocationStrategy {
} }
if (isBlank(href)) { 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.`); `No base href set. Please provide a value for the APP_BASE_HREF token or add a base element to the document.`);
} }

View File

@ -9,7 +9,7 @@
import {ChangeDetectorRef, OnDestroy, Pipe, WrappedValue} from '@angular/core'; import {ChangeDetectorRef, OnDestroy, Pipe, WrappedValue} from '@angular/core';
import {EventEmitter, Observable} from '../facade/async'; import {EventEmitter, Observable} from '../facade/async';
import {isBlank, isPresent, isPromise} from '../facade/lang'; import {isBlank, isPresent, isPromise} from '../facade/lang';
import {InvalidPipeArgumentException} from './invalid_pipe_argument_exception'; import {InvalidPipeArgumentError} from './invalid_pipe_argument_error';
interface SubscriptionStrategy { interface SubscriptionStrategy {
createSubscription(async: any, updateLatestValue: any): any; createSubscription(async: any, updateLatestValue: any): any;
@ -128,7 +128,7 @@ export class AsyncPipe implements OnDestroy {
} else if ((<any>obj).subscribe) { } else if ((<any>obj).subscribe) {
return _observableStrategy; return _observableStrategy;
} else { } else {
throw new InvalidPipeArgumentException(AsyncPipe, obj); throw new InvalidPipeArgumentError(AsyncPipe, obj);
} }
} }

View File

@ -11,8 +11,7 @@ import {Inject, LOCALE_ID, Pipe, PipeTransform} from '@angular/core';
import {StringMapWrapper} from '../facade/collection'; import {StringMapWrapper} from '../facade/collection';
import {DateFormatter} from '../facade/intl'; import {DateFormatter} from '../facade/intl';
import {DateWrapper, NumberWrapper, isBlank, isDate, isString} from '../facade/lang'; import {DateWrapper, NumberWrapper, isBlank, isDate, isString} from '../facade/lang';
import {InvalidPipeArgumentError} from './invalid_pipe_argument_error';
import {InvalidPipeArgumentException} from './invalid_pipe_argument_exception';
/** /**
@ -102,7 +101,7 @@ export class DatePipe implements PipeTransform {
if (isBlank(value)) return null; if (isBlank(value)) return null;
if (!this.supports(value)) { if (!this.supports(value)) {
throw new InvalidPipeArgumentException(DatePipe, value); throw new InvalidPipeArgumentError(DatePipe, value);
} }
if (NumberWrapper.isNumeric(value)) { if (NumberWrapper.isNumeric(value)) {

View File

@ -9,7 +9,7 @@
import {Pipe, PipeTransform} from '@angular/core'; import {Pipe, PipeTransform} from '@angular/core';
import {StringWrapper, isBlank, isStringMap} from '../facade/lang'; import {StringWrapper, isBlank, isStringMap} from '../facade/lang';
import {NgLocalization, getPluralCategory} from '../localization'; import {NgLocalization, getPluralCategory} from '../localization';
import {InvalidPipeArgumentException} from './invalid_pipe_argument_exception'; import {InvalidPipeArgumentError} from './invalid_pipe_argument_error';
const _INTERPOLATION_REGEXP: RegExp = /#/g; const _INTERPOLATION_REGEXP: RegExp = /#/g;
@ -58,7 +58,7 @@ export class I18nPluralPipe implements PipeTransform {
if (isBlank(value)) return ''; if (isBlank(value)) return '';
if (!isStringMap(pluralMap)) { if (!isStringMap(pluralMap)) {
throw new InvalidPipeArgumentException(I18nPluralPipe, pluralMap); throw new InvalidPipeArgumentError(I18nPluralPipe, pluralMap);
} }
const key = getPluralCategory(value, Object.keys(pluralMap), this._localization); const key = getPluralCategory(value, Object.keys(pluralMap), this._localization);

View File

@ -8,7 +8,7 @@
import {Pipe, PipeTransform} from '@angular/core'; import {Pipe, PipeTransform} from '@angular/core';
import {isBlank, isStringMap} from '../facade/lang'; 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 (isBlank(value)) return '';
if (!isStringMap(mapping)) { if (!isStringMap(mapping)) {
throw new InvalidPipeArgumentException(I18nSelectPipe, mapping); throw new InvalidPipeArgumentError(I18nSelectPipe, mapping);
} }
return mapping.hasOwnProperty(value) ? mapping[value] : ''; return mapping.hasOwnProperty(value) ? mapping[value] : '';

View File

@ -6,10 +6,12 @@
* found in the LICENSE file at https://angular.io/license * 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'; import {stringify} from '../facade/lang';
export class InvalidPipeArgumentException extends BaseException { export class InvalidPipeArgumentError extends BaseError {
constructor(type: Type<any>, value: Object) { constructor(type: Type<any>, value: Object) {
super(`Invalid argument '${value}' for pipe '${stringify(type)}'`); super(`Invalid argument '${value}' for pipe '${stringify(type)}'`);
} }

View File

@ -8,7 +8,7 @@
import {Pipe, PipeTransform} from '@angular/core'; import {Pipe, PipeTransform} from '@angular/core';
import {isBlank, isString} from '../facade/lang'; 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 { transform(value: string): string {
if (isBlank(value)) return value; if (isBlank(value)) return value;
if (!isString(value)) { if (!isString(value)) {
throw new InvalidPipeArgumentException(LowerCasePipe, value); throw new InvalidPipeArgumentError(LowerCasePipe, value);
} }
return value.toLowerCase(); return value.toLowerCase();
} }

View File

@ -11,7 +11,7 @@ import {Inject, LOCALE_ID, Pipe, PipeTransform, Type} from '@angular/core';
import {NumberFormatStyle, NumberFormatter} from '../facade/intl'; import {NumberFormatStyle, NumberFormatter} from '../facade/intl';
import {NumberWrapper, isBlank, isNumber, isPresent, isString} from '../facade/lang'; 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+))?)?$/; const _NUMBER_FORMAT_REGEXP = /^(\d+)?\.((\d+)(\-(\d+))?)?$/;
@ -22,7 +22,7 @@ function formatNumber(
// Convert strings to numbers // Convert strings to numbers
value = isString(value) && NumberWrapper.isNumeric(value) ? +value : value; value = isString(value) && NumberWrapper.isNumeric(value) ? +value : value;
if (!isNumber(value)) { if (!isNumber(value)) {
throw new InvalidPipeArgumentException(pipe, value); throw new InvalidPipeArgumentError(pipe, value);
} }
let minInt: number; let minInt: number;
let minFraction: number; let minFraction: number;

View File

@ -9,7 +9,7 @@
import {Pipe, PipeTransform} from '@angular/core'; import {Pipe, PipeTransform} from '@angular/core';
import {ListWrapper} from '../facade/collection'; import {ListWrapper} from '../facade/collection';
import {StringWrapper, isArray, isBlank, isString} from '../facade/lang'; 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 * 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 { transform(value: any, start: number, end: number = null): any {
if (isBlank(value)) return value; if (isBlank(value)) return value;
if (!this.supports(value)) { if (!this.supports(value)) {
throw new InvalidPipeArgumentException(SlicePipe, value); throw new InvalidPipeArgumentError(SlicePipe, value);
} }
if (isString(value)) { if (isString(value)) {
return StringWrapper.slice(value, start, end); return StringWrapper.slice(value, start, end);

View File

@ -8,7 +8,7 @@
import {Pipe, PipeTransform} from '@angular/core'; import {Pipe, PipeTransform} from '@angular/core';
import {isBlank, isString} from '../facade/lang'; 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. * Implements uppercase transforms to text.
@ -24,7 +24,7 @@ export class UpperCasePipe implements PipeTransform {
transform(value: string): string { transform(value: string): string {
if (isBlank(value)) return value; if (isBlank(value)) return value;
if (!isString(value)) { if (!isString(value)) {
throw new InvalidPipeArgumentException(UpperCasePipe, value); throw new InvalidPipeArgumentError(UpperCasePipe, value);
} }
return value.toUpperCase(); return value.toUpperCase();
} }

View File

@ -97,3 +97,7 @@ export var collectAndResolveStyles: typeof r.collectAndResolveStyles = r.collect
export var renderStyles: typeof r.renderStyles = r.renderStyles; export var renderStyles: typeof r.renderStyles = r.renderStyles;
export type ViewMetadata = typeof _compiler_core_private_types.ViewMetadata; export type ViewMetadata = typeof _compiler_core_private_types.ViewMetadata;
export var ViewMetadata: typeof r.ViewMetadata = r.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;

View File

@ -6,8 +6,6 @@
* found in the LICENSE file at https://angular.io/license * 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 {ANY_STATE, AnimationOutput, DEFAULT_STATE, EMPTY_STATE} from '../../core_private';
import {CompileDirectiveMetadata} from '../compile_metadata'; import {CompileDirectiveMetadata} from '../compile_metadata';
import {StringMapWrapper} from '../facade/collection'; import {StringMapWrapper} from '../facade/collection';
@ -72,7 +70,7 @@ export class AnimationCompiler {
var errorMessageStr = var errorMessageStr =
`Animation parsing for ${component.type.name} has failed due to the following errors:`; `Animation parsing for ${component.type.name} has failed due to the following errors:`;
groupedErrors.forEach(error => errorMessageStr += `\n- ${error}`); groupedErrors.forEach(error => errorMessageStr += `\n- ${error}`);
throw new BaseException(errorMessageStr); throw new Error(errorMessageStr);
} }
animationCompilationCache.set(component, compiledAnimations); animationCompilationCache.set(component, compiledAnimations);

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license * 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'; import {LifecycleHooks, reflector} from '../core_private';
@ -17,7 +17,7 @@ import {getUrlScheme} from './url_resolver';
import {sanitizeIdentifier, splitAtColon} from './util'; import {sanitizeIdentifier, splitAtColon} from './util';
function unimplemented(): any { function unimplemented(): any {
throw new BaseException('unimplemented'); throw new Error('unimplemented');
} }
// group 0: "[prop] or (event) or @trigger" // group 0: "[prop] or (event) or @trigger"
@ -269,7 +269,7 @@ export class CompileIdentifierMap<KEY extends CompileMetadataWithIdentifier, VAL
add(token: KEY, value: VALUE) { add(token: KEY, value: VALUE) {
var existing = this.get(token); var existing = this.get(token);
if (isPresent(existing)) { if (isPresent(existing)) {
throw new BaseException( throw new Error(
`Cannot overwrite in a CompileIdentifierMap! Token: ${token.identifier.name}`); `Cannot overwrite in a CompileIdentifierMap! Token: ${token.identifier.name}`);
} }
this._tokens.push(token); this._tokens.push(token);
@ -398,7 +398,7 @@ export class CompileTemplateMetadata {
this.animations = isPresent(animations) ? ListWrapper.flatten(animations) : []; this.animations = isPresent(animations) ? ListWrapper.flatten(animations) : [];
this.ngContentSelectors = isPresent(ngContentSelectors) ? ngContentSelectors : []; this.ngContentSelectors = isPresent(ngContentSelectors) ? ngContentSelectors : [];
if (isPresent(interpolation) && interpolation.length != 2) { if (isPresent(interpolation) && interpolation.length != 2) {
throw new BaseException(`'interpolation' should have a start and an end symbol.`); throw new Error(`'interpolation' should have a start and an end symbol.`);
} }
this.interpolation = interpolation; this.interpolation = interpolation;
} }

View File

@ -6,13 +6,13 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {BaseException, ViewEncapsulation, isDevMode} from '@angular/core'; import {ViewEncapsulation, isDevMode} from '@angular/core';
import {CompileIdentifierMetadata} from './compile_metadata'; import {CompileIdentifierMetadata} from './compile_metadata';
import {Identifiers} from './identifiers'; import {Identifiers} from './identifiers';
function unimplemented(): any { function unimplemented(): any {
throw new BaseException('unimplemented'); throw new Error('unimplemented');
} }
export class CompilerConfig { export class CompilerConfig {

View File

@ -6,9 +6,9 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {BaseException} from '@angular/core';
import * as chars from '../chars'; import * as chars from '../chars';
import {BaseError} from '../facade/errors';
import {StringWrapper, isPresent, resolveEnumToken} from '../facade/lang'; import {StringWrapper, isPresent, resolveEnumToken} from '../facade/lang';
export enum CssTokenType { export enum CssTokenType {
@ -86,7 +86,7 @@ export class CssLexer {
} }
} }
export class CssScannerError extends BaseException { export class CssScannerError extends BaseError {
public rawMessage: string; public rawMessage: string;
public message: string; public message: string;

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {BaseException, Injectable, ViewEncapsulation} from '@angular/core'; import {Injectable, ViewEncapsulation} from '@angular/core';
import {CompileDirectiveMetadata, CompileStylesheetMetadata, CompileTemplateMetadata, CompileTypeMetadata} from './compile_metadata'; import {CompileDirectiveMetadata, CompileStylesheetMetadata, CompileTemplateMetadata, CompileTypeMetadata} from './compile_metadata';
import {CompilerConfig} from './config'; import {CompilerConfig} from './config';
@ -63,7 +63,7 @@ export class DirectiveNormalizer {
} else if (directive.template.templateUrl) { } else if (directive.template.templateUrl) {
normalizedTemplateAsync = this.normalizeTemplateAsync(directive.type, directive.template); normalizedTemplateAsync = this.normalizeTemplateAsync(directive.type, directive.template);
} else { } else {
throw new BaseException(`No template specified for component ${directive.type.name}`); throw new Error(`No template specified for component ${directive.type.name}`);
} }
if (normalizedTemplateSync && normalizedTemplateSync.styleUrls.length === 0) { if (normalizedTemplateSync && normalizedTemplateSync.styleUrls.length === 0) {
// sync case // sync case
@ -102,7 +102,7 @@ export class DirectiveNormalizer {
this._htmlParser.parse(template, directiveType.name, false, interpolationConfig); this._htmlParser.parse(template, directiveType.name, false, interpolationConfig);
if (rootNodesAndErrors.errors.length > 0) { if (rootNodesAndErrors.errors.length > 0) {
const errorString = rootNodesAndErrors.errors.join('\n'); 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({ const templateMetadataStyles = this.normalizeStylesheet(new CompileStylesheetMetadata({
styles: templateMeta.styles, styles: templateMeta.styles,

View File

@ -9,7 +9,6 @@
import {ComponentMetadata, DirectiveMetadata, HostBindingMetadata, HostListenerMetadata, Injectable, InputMetadata, OutputMetadata, QueryMetadata, Type, resolveForwardRef} from '@angular/core'; import {ComponentMetadata, DirectiveMetadata, HostBindingMetadata, HostListenerMetadata, Injectable, InputMetadata, OutputMetadata, QueryMetadata, Type, resolveForwardRef} from '@angular/core';
import {ReflectorReader, reflector} from '../core_private'; import {ReflectorReader, reflector} from '../core_private';
import {StringMapWrapper} from './facade/collection'; import {StringMapWrapper} from './facade/collection';
import {BaseException} from './facade/exceptions';
import {isPresent, stringify} from './facade/lang'; import {isPresent, stringify} from './facade/lang';
import {splitAtColon} from './util'; import {splitAtColon} from './util';
@ -41,7 +40,7 @@ export class DirectiveResolver {
} }
} }
if (throwIfNotFound) { if (throwIfNotFound) {
throw new BaseException(`No Directive annotation found on ${stringify(type)}`); throw new Error(`No Directive annotation found on ${stringify(type)}`);
} }
return null; return null;
} }
@ -98,7 +97,7 @@ export class DirectiveResolver {
inputs.forEach((inputDef: string) => { inputs.forEach((inputDef: string) => {
const publicName = this._extractPublicName(inputDef); const publicName = this._extractPublicName(inputDef);
if (inputNames.indexOf(publicName) > -1) { if (inputNames.indexOf(publicName) > -1) {
throw new BaseException( throw new Error(
`Input '${publicName}' defined multiple times in '${stringify(directiveType)}'`); `Input '${publicName}' defined multiple times in '${stringify(directiveType)}'`);
} }
}); });
@ -116,7 +115,7 @@ export class DirectiveResolver {
outputs.forEach((outputDef: string) => { outputs.forEach((outputDef: string) => {
const publicName = this._extractPublicName(outputDef); const publicName = this._extractPublicName(outputDef);
if (outputNames.indexOf(publicName) > -1) { if (outputNames.indexOf(publicName) > -1) {
throw new BaseException( throw new Error(
`Output event '${publicName}' defined multiple times in '${stringify(directiveType)}'`); `Output event '${publicName}' defined multiple times in '${stringify(directiveType)}'`);
} }
}); });

View File

@ -14,7 +14,6 @@ import {StringMapWrapper} from '../src/facade/collection';
import {assertArrayOfStrings, assertInterpolationSymbols} from './assertions'; import {assertArrayOfStrings, assertInterpolationSymbols} from './assertions';
import * as cpl from './compile_metadata'; import * as cpl from './compile_metadata';
import {DirectiveResolver} from './directive_resolver'; import {DirectiveResolver} from './directive_resolver';
import {BaseException} from './facade/exceptions';
import {isArray, isBlank, isPresent, isString, stringify} from './facade/lang'; import {isArray, isBlank, isPresent, isString, stringify} from './facade/lang';
import {Identifiers, identifierToken} from './identifiers'; import {Identifiers, identifierToken} from './identifiers';
import {hasLifecycleHook} from './lifecycle_reflector'; import {hasLifecycleHook} from './lifecycle_reflector';
@ -161,8 +160,7 @@ export class CompileMetadataResolver {
} }
} else { } else {
if (!selector) { if (!selector) {
throw new BaseException( throw new Error(`Directive ${stringify(directiveType)} has no selector, please add it!`);
`Directive ${stringify(directiveType)} has no selector, please add it!`);
} }
} }
@ -235,12 +233,12 @@ export class CompileMetadataResolver {
if (importedModuleType) { if (importedModuleType) {
let importedMeta = this.getNgModuleMetadata(importedModuleType, false); let importedMeta = this.getNgModuleMetadata(importedModuleType, false);
if (importedMeta === null) { if (importedMeta === null) {
throw new BaseException( throw new Error(
`Unexpected ${this._getTypeDescriptor(importedType)} '${stringify(importedType)}' imported by the module '${stringify(moduleType)}'`); `Unexpected ${this._getTypeDescriptor(importedType)} '${stringify(importedType)}' imported by the module '${stringify(moduleType)}'`);
} }
importedModules.push(importedMeta); importedModules.push(importedMeta);
} else { } else {
throw new BaseException( throw new Error(
`Unexpected value '${stringify(importedType)}' imported by the module '${stringify(moduleType)}'`); `Unexpected value '${stringify(importedType)}' imported by the module '${stringify(moduleType)}'`);
} }
}); });
@ -249,7 +247,7 @@ export class CompileMetadataResolver {
if (meta.exports) { if (meta.exports) {
flattenArray(meta.exports).forEach((exportedType) => { flattenArray(meta.exports).forEach((exportedType) => {
if (!isValidType(exportedType)) { if (!isValidType(exportedType)) {
throw new BaseException( throw new Error(
`Unexpected value '${stringify(exportedType)}' exported by the module '${stringify(moduleType)}'`); `Unexpected value '${stringify(exportedType)}' exported by the module '${stringify(moduleType)}'`);
} }
let exportedDirMeta: cpl.CompileDirectiveMetadata; let exportedDirMeta: cpl.CompileDirectiveMetadata;
@ -262,7 +260,7 @@ export class CompileMetadataResolver {
} else if (exportedModuleMeta = this.getNgModuleMetadata(exportedType, false)) { } else if (exportedModuleMeta = this.getNgModuleMetadata(exportedType, false)) {
exportedModules.push(exportedModuleMeta); exportedModules.push(exportedModuleMeta);
} else { } else {
throw new BaseException( throw new Error(
`Unexpected ${this._getTypeDescriptor(exportedType)} '${stringify(exportedType)}' exported by the module '${stringify(moduleType)}'`); `Unexpected ${this._getTypeDescriptor(exportedType)} '${stringify(exportedType)}' exported by the module '${stringify(moduleType)}'`);
} }
}); });
@ -275,7 +273,7 @@ export class CompileMetadataResolver {
if (meta.declarations) { if (meta.declarations) {
flattenArray(meta.declarations).forEach((declaredType) => { flattenArray(meta.declarations).forEach((declaredType) => {
if (!isValidType(declaredType)) { if (!isValidType(declaredType)) {
throw new BaseException( throw new Error(
`Unexpected value '${stringify(declaredType)}' declared by the module '${stringify(moduleType)}'`); `Unexpected value '${stringify(declaredType)}' declared by the module '${stringify(moduleType)}'`);
} }
let declaredDirMeta: cpl.CompileDirectiveMetadata; let declaredDirMeta: cpl.CompileDirectiveMetadata;
@ -287,7 +285,7 @@ export class CompileMetadataResolver {
this._addPipeToModule( this._addPipeToModule(
declaredPipeMeta, moduleType, transitiveModule, declaredPipes, true); declaredPipeMeta, moduleType, transitiveModule, declaredPipes, true);
} else { } else {
throw new BaseException( throw new Error(
`Unexpected ${this._getTypeDescriptor(declaredType)} '${stringify(declaredType)}' declared by the module '${stringify(moduleType)}'`); `Unexpected ${this._getTypeDescriptor(declaredType)} '${stringify(declaredType)}' declared by the module '${stringify(moduleType)}'`);
} }
}); });
@ -343,13 +341,13 @@ export class CompileMetadataResolver {
private _verifyModule(moduleMeta: cpl.CompileNgModuleMetadata) { private _verifyModule(moduleMeta: cpl.CompileNgModuleMetadata) {
moduleMeta.exportedDirectives.forEach((dirMeta) => { moduleMeta.exportedDirectives.forEach((dirMeta) => {
if (!moduleMeta.transitiveModule.directivesSet.has(dirMeta.type.runtime)) { 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!`); `Can't export directive ${stringify(dirMeta.type.runtime)} from ${stringify(moduleMeta.type.runtime)} as it was neither declared nor imported!`);
} }
}); });
moduleMeta.exportedPipes.forEach((pipeMeta) => { moduleMeta.exportedPipes.forEach((pipeMeta) => {
if (!moduleMeta.transitiveModule.pipesSet.has(pipeMeta.type.runtime)) { 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!`); `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<any>, moduleType: Type<any>) { private _addTypeToModule(type: Type<any>, moduleType: Type<any>) {
const oldModule = this._ngModuleOfTypes.get(type); const oldModule = this._ngModuleOfTypes.get(type);
if (oldModule && oldModule !== moduleType) { 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)}!`); `Type ${stringify(type)} is part of the declarations of 2 modules: ${stringify(oldModule)} and ${stringify(moduleType)}!`);
} }
this._ngModuleOfTypes.set(type, moduleType); this._ngModuleOfTypes.set(type, moduleType);
@ -529,7 +527,7 @@ export class CompileMetadataResolver {
let depsTokens = let depsTokens =
dependenciesMetadata.map((dep) => { return dep ? stringify(dep.token) : '?'; }) dependenciesMetadata.map((dep) => { return dep ? stringify(dep.token) : '?'; })
.join(', '); .join(', ');
throw new BaseException( throw new Error(
`Can't resolve all parameters for ${stringify(typeOrFunc)}: (${depsTokens}).`); `Can't resolve all parameters for ${stringify(typeOrFunc)}: (${depsTokens}).`);
} }
@ -589,7 +587,7 @@ export class CompileMetadataResolver {
[])) []))
.join(', '); .join(', ');
throw new BaseException( throw new Error(
`Invalid ${debugInfo ? debugInfo : 'provider'} - only instances of Provider and Type are allowed, got: [${providersInfo}]`); `Invalid ${debugInfo ? debugInfo : 'provider'} - only instances of Provider and Type are allowed, got: [${providersInfo}]`);
} }
if (compileProvider) { if (compileProvider) {
@ -603,11 +601,10 @@ export class CompileMetadataResolver {
let components: cpl.CompileTypeMetadata[] = []; let components: cpl.CompileTypeMetadata[] = [];
let collectedIdentifiers: cpl.CompileIdentifierMetadata[] = []; let collectedIdentifiers: cpl.CompileIdentifierMetadata[] = [];
if (provider.useFactory || provider.useExisting || provider.useClass) { 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) { if (!provider.multi) {
throw new BaseException( throw new Error(`The ANALYZE_FOR_ENTRY_COMPONENTS token only supports 'multi = true'!`);
`The ANALYZE_FOR_ENTRY_COMPONENTS token only supports 'multi = true'!`);
} }
convertToCompileValue(provider.useValue, collectedIdentifiers); convertToCompileValue(provider.useValue, collectedIdentifiers);
collectedIdentifiers.forEach((identifier) => { collectedIdentifiers.forEach((identifier) => {
@ -665,7 +662,7 @@ export class CompileMetadataResolver {
selectors = q.varBindings.map(varName => this.getTokenMetadata(varName)); selectors = q.varBindings.map(varName => this.getTokenMetadata(varName));
} else { } else {
if (!isPresent(q.selector)) { 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.`); `Can't construct a query for the property "${propertyName}" of "${stringify(typeOrFunc)}" since the query selector wasn't defined.`);
} }
selectors = [this.getTokenMetadata(q.selector)]; selectors = [this.getTokenMetadata(q.selector)];

View File

@ -9,7 +9,6 @@
import {Injectable, NgModuleMetadata, Type} from '@angular/core'; import {Injectable, NgModuleMetadata, Type} from '@angular/core';
import {ReflectorReader, reflector} from '../core_private'; import {ReflectorReader, reflector} from '../core_private';
import {BaseException} from '../src/facade/exceptions';
import {isPresent, stringify} from './facade/lang'; import {isPresent, stringify} from './facade/lang';
function _isNgModuleMetadata(obj: any): obj is NgModuleMetadata { function _isNgModuleMetadata(obj: any): obj is NgModuleMetadata {
@ -31,7 +30,7 @@ export class NgModuleResolver {
return ngModuleMeta; return ngModuleMeta;
} else { } else {
if (throwIfNotFound) { if (throwIfNotFound) {
throw new BaseException(`No NgModule metadata found for '${stringify(type)}'.`); throw new Error(`No NgModule metadata found for '${stringify(type)}'.`);
} }
return null; return null;
} }

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license * 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 {CompileDirectiveMetadata, CompileIdentifierMetadata, CompileNgModuleMetadata, CompilePipeMetadata, CompileProviderMetadata, CompileTokenMetadata, StaticSymbol, createHostComponentMeta} from './compile_metadata';
import {DirectiveNormalizer} from './directive_normalizer'; import {DirectiveNormalizer} from './directive_normalizer';
@ -73,8 +73,7 @@ export class OfflineCompiler {
const compMeta = this._metadataResolver.getDirectiveMetadata(<any>compType); const compMeta = this._metadataResolver.getDirectiveMetadata(<any>compType);
const ngModule = ngModulesSummary.ngModuleByComponent.get(compType); const ngModule = ngModulesSummary.ngModuleByComponent.get(compType);
if (!ngModule) { if (!ngModule) {
throw new BaseException( throw new Error(`Cannot determine the module for component ${compMeta.type.name}!`);
`Cannot determine the module for component ${compMeta.type.name}!`);
} }
return Promise return Promise
.all([compMeta, ...ngModule.transitiveModule.directives].map( .all([compMeta, ...ngModule.transitiveModule.directives].map(
@ -217,7 +216,7 @@ function _stylesModuleUrl(stylesheetUrl: string, shim: boolean, suffix: string):
function _assertComponent(meta: CompileDirectiveMetadata) { function _assertComponent(meta: CompileDirectiveMetadata) {
if (!meta.isComponent) { 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.`);
} }
} }

View File

@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {BaseException} from '@angular/core';
import {StringWrapper, isBlank, isPresent, isString} from '../facade/lang'; import {StringWrapper, isBlank, isPresent, isString} from '../facade/lang';
import * as o from './output_ast'; import * as o from './output_ast';
@ -236,7 +235,7 @@ export abstract class AbstractEmitterVisitor implements o.StatementVisitor, o.Ex
varName = CATCH_STACK_VAR.name; varName = CATCH_STACK_VAR.name;
break; break;
default: default:
throw new BaseException(`Unknown builtin variable ${ast.builtin}`); throw new Error(`Unknown builtin variable ${ast.builtin}`);
} }
} }
ctx.print(varName); ctx.print(varName);
@ -332,7 +331,7 @@ export abstract class AbstractEmitterVisitor implements o.StatementVisitor, o.Ex
opStr = '>='; opStr = '>=';
break; break;
default: default:
throw new BaseException(`Unknown operator ${ast.operator}`); throw new Error(`Unknown operator ${ast.operator}`);
} }
ctx.print(`(`); ctx.print(`(`);
ast.lhs.visitExpression(this, ctx); ast.lhs.visitExpression(this, ctx);

View File

@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {BaseException} from '@angular/core';
import {isPresent} from '../facade/lang'; import {isPresent} from '../facade/lang';
import {AbstractEmitterVisitor, CATCH_ERROR_VAR, CATCH_STACK_VAR, EmitterVisitorContext} from './abstract_emitter'; 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) { if (ast.builtin === o.BuiltinVar.This) {
ctx.print('self'); ctx.print('self');
} else if (ast.builtin === o.BuiltinVar.Super) { } 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!`); `'super' needs to be handled at a parent ast node, not at the variable level!`);
} else { } else {
super.visitReadVarExpr(ast, ctx); super.visitReadVarExpr(ast, ctx);
@ -161,7 +160,7 @@ export abstract class AbstractJsEmitterVisitor extends AbstractEmitterVisitor {
name = 'bind'; name = 'bind';
break; break;
default: default:
throw new BaseException(`Unknown builtin method: ${method}`); throw new Error(`Unknown builtin method: ${method}`);
} }
return name; return name;
} }

View File

@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {BaseException} from '@angular/core';
import {StringWrapper, evalExpression, isBlank, isPresent, isString} from '../facade/lang'; import {StringWrapper, evalExpression, isBlank, isPresent, isString} from '../facade/lang';
@ -40,7 +39,7 @@ class JsEmitterVisitor extends AbstractJsEmitterVisitor {
visitExternalExpr(ast: o.ExternalExpr, ctx: EmitterVisitorContext): any { visitExternalExpr(ast: o.ExternalExpr, ctx: EmitterVisitorContext): any {
if (isBlank(ast.value.name)) { 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) { if (isPresent(ast.value.moduleUrl) && ast.value.moduleUrl != this._moduleUrl) {
var prefix = this.importsWithPrefixes.get(ast.value.moduleUrl); var prefix = this.importsWithPrefixes.get(ast.value.moduleUrl);

View File

@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {BaseException} from '@angular/core';
import {CompileIdentifierMetadata} from '../compile_metadata'; import {CompileIdentifierMetadata} from '../compile_metadata';
import {StringMapWrapper} from '../facade/collection'; import {StringMapWrapper} from '../facade/collection';

View File

@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {BaseException} from '@angular/core';
import {ListWrapper} from '../facade/collection'; import {ListWrapper} from '../facade/collection';
import {isPresent} from '../facade/lang'; import {isPresent} from '../facade/lang';
@ -104,7 +103,7 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor {
} }
currCtx = currCtx.parent; 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 { visitReadVarExpr(ast: o.ReadVarExpr, ctx: _ExecutionContext): any {
var varName = ast.name; var varName = ast.name;
@ -121,7 +120,7 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor {
varName = CATCH_STACK_VAR; varName = CATCH_STACK_VAR;
break; break;
default: default:
throw new BaseException(`Unknown builtin variable ${ast.builtin}`); throw new Error(`Unknown builtin variable ${ast.builtin}`);
} }
} }
var currCtx = ctx; var currCtx = ctx;
@ -131,7 +130,7 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor {
} }
currCtx = currCtx.parent; currCtx = currCtx.parent;
} }
throw new BaseException(`Not declared variable ${varName}`); throw new Error(`Not declared variable ${varName}`);
} }
visitWriteKeyExpr(expr: o.WriteKeyExpr, ctx: _ExecutionContext): any { visitWriteKeyExpr(expr: o.WriteKeyExpr, ctx: _ExecutionContext): any {
var receiver = expr.receiver.visitExpression(this, ctx); var receiver = expr.receiver.visitExpression(this, ctx);
@ -163,7 +162,7 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor {
result = receiver.bind(args[0]); result = receiver.bind(args[0]);
break; break;
default: default:
throw new BaseException(`Unknown builtin method ${expr.builtin}`); throw new Error(`Unknown builtin method ${expr.builtin}`);
} }
} else { } else {
result = receiver[expr.name].apply(receiver, args); result = receiver[expr.name].apply(receiver, args);
@ -281,7 +280,7 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor {
case o.BinaryOperator.BiggerEquals: case o.BinaryOperator.BiggerEquals:
return lhs() >= rhs(); return lhs() >= rhs();
default: default:
throw new BaseException(`Unknown operator ${ast.operator}`); throw new Error(`Unknown operator ${ast.operator}`);
} }
} }
visitReadPropExpr(ast: o.ReadPropExpr, ctx: _ExecutionContext): any { visitReadPropExpr(ast: o.ReadPropExpr, ctx: _ExecutionContext): any {

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license * 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'; import {Math, isBlank, isPresent} from '../facade/lang';
@ -32,7 +32,7 @@ export class AssetUrl {
if (allowNonMatching) { if (allowNonMatching) {
return null; 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) { constructor(public packageName: string, public firstLevelDir: string, public modulePath: string) {

View File

@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {BaseException} from '@angular/core';
import {CompileIdentifierMetadata} from '../compile_metadata'; import {CompileIdentifierMetadata} from '../compile_metadata';
import {isArray, isBlank, isPresent} from '../facade/lang'; 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) { } else if (ast instanceof o.Type) {
ast.visitType(converter, ctx); ast.visitType(converter, ctx);
} else { } 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(); return ctx.toSource();
@ -249,7 +248,7 @@ class _TsEmitterVisitor extends AbstractEmitterVisitor implements o.TypeVisitor
typeStr = 'string'; typeStr = 'string';
break; break;
default: default:
throw new BaseException(`Unsupported builtin type ${type.name}`); throw new Error(`Unsupported builtin type ${type.name}`);
} }
ctx.print(typeStr); ctx.print(typeStr);
return null; return null;
@ -286,7 +285,7 @@ class _TsEmitterVisitor extends AbstractEmitterVisitor implements o.TypeVisitor
name = 'bind'; name = 'bind';
break; break;
default: default:
throw new BaseException(`Unknown builtin method: ${method}`); throw new Error(`Unknown builtin method: ${method}`);
} }
return name; return name;
} }
@ -302,7 +301,7 @@ class _TsEmitterVisitor extends AbstractEmitterVisitor implements o.TypeVisitor
private _visitIdentifier( private _visitIdentifier(
value: CompileIdentifierMetadata, typeParams: o.Type[], ctx: EmitterVisitorContext): void { value: CompileIdentifierMetadata, typeParams: o.Type[], ctx: EmitterVisitorContext): void {
if (isBlank(value.name)) { 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) { if (isPresent(value.moduleUrl) && value.moduleUrl != this._moduleUrl) {
var prefix = this.importsWithPrefixes.get(value.moduleUrl); var prefix = this.importsWithPrefixes.get(value.moduleUrl);

View File

@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {BaseException} from '@angular/core';
import {CompileIdentifierMetadata} from '../compile_metadata'; import {CompileIdentifierMetadata} from '../compile_metadata';
import {StringMapWrapper} from '../facade/collection'; import {StringMapWrapper} from '../facade/collection';
@ -39,7 +38,7 @@ class _ValueOutputAstTransformer implements ValueTransformer {
} else if (value instanceof o.Expression) { } else if (value instanceof o.Expression) {
return value; return value;
} else { } 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}`);
} }
} }
} }

View File

@ -10,7 +10,6 @@ import {Injectable, PipeMetadata, Type, resolveForwardRef} from '@angular/core';
import {ReflectorReader, reflector} from '../core_private'; import {ReflectorReader, reflector} from '../core_private';
import {BaseException} from './facade/exceptions';
import {isPresent, stringify} from './facade/lang'; import {isPresent, stringify} from './facade/lang';
function _isPipeMetadata(type: any): boolean { function _isPipeMetadata(type: any): boolean {
@ -40,7 +39,7 @@ export class PipeResolver {
} }
} }
if (throwIfNotFound) { if (throwIfNotFound) {
throw new BaseException(`No Pipe decorator found on ${stringify(type)}`); throw new Error(`No Pipe decorator found on ${stringify(type)}`);
} }
return null; return null;
} }

View File

@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license * 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 {CompileDiDependencyMetadata, CompileDirectiveMetadata, CompileIdentifierMap, CompileNgModuleMetadata, CompileProviderMetadata, CompileQueryMetadata, CompileTokenMetadata, CompileTypeMetadata} from './compile_metadata';
import {ListWrapper} from './facade/collection'; import {ListWrapper} from './facade/collection';
@ -303,7 +302,7 @@ export class NgModuleProviderAnalyzer {
(provider) => { this._getOrCreateLocalProvider(provider.token, provider.eager); }); (provider) => { this._getOrCreateLocalProvider(provider.token, provider.eager); });
if (this._errors.length > 0) { if (this._errors.length > 0) {
const errorString = this._errors.join('\n'); 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(); return this._transformedProviders.values();
} }

View File

@ -6,14 +6,11 @@
* found in the LICENSE file at https://angular.io/license * 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 {Compiler, ComponentFactory, Injectable, Injector, ModuleWithComponentFactories, NgModuleFactory, OptionalMetadata, Provider, SchemaMetadata, SkipSelfMetadata, Type} from '@angular/core';
import {ComponentStillLoadingError} from '../core_private';
import {Console} from '../core_private';
import {CompileDirectiveMetadata, CompileIdentifierMetadata, CompileNgModuleMetadata, CompilePipeMetadata, ProviderMeta, createHostComponentMeta} from './compile_metadata'; import {CompileDirectiveMetadata, CompileIdentifierMetadata, CompileNgModuleMetadata, CompilePipeMetadata, ProviderMeta, createHostComponentMeta} from './compile_metadata';
import {CompilerConfig} from './config'; import {CompilerConfig} from './config';
import {DirectiveNormalizer} from './directive_normalizer'; import {DirectiveNormalizer} from './directive_normalizer';
import {BaseException} from './facade/exceptions';
import {isBlank, stringify} from './facade/lang'; import {isBlank, stringify} from './facade/lang';
import {CompileMetadataResolver} from './metadata_resolver'; import {CompileMetadataResolver} from './metadata_resolver';
import {NgModuleCompiler} from './ng_module_compiler'; import {NgModuleCompiler} from './ng_module_compiler';
@ -223,10 +220,10 @@ export class RuntimeCompiler implements Compiler {
this._compiledTemplateCache.get(compType); this._compiledTemplateCache.get(compType);
if (!compiledTemplate) { if (!compiledTemplate) {
if (isHost) { if (isHost) {
throw new BaseException( throw new Error(
`Illegal state: Compiled view for component ${stringify(compType)} does not exist!`); `Illegal state: Compiled view for component ${stringify(compType)} does not exist!`);
} else { } 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.`); `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 { private _assertComponentLoaded(compType: any, isHost: boolean): CompiledTemplate {
const compiledTemplate = this._assertComponentKnown(compType, isHost); const compiledTemplate = this._assertComponentKnown(compType, isHost);
if (compiledTemplate.loading) { if (compiledTemplate.loading) {
throw new BaseException( throw new Error(
`Illegal state: CompiledTemplate for ${stringify(compType)} (isHost: ${isHost}) is still loading!`); `Illegal state: CompiledTemplate for ${stringify(compType)} (isHost: ${isHost}) is still loading!`);
} }
return compiledTemplate; return compiledTemplate;
@ -335,7 +332,7 @@ class CompiledTemplate {
}); });
this.proxyViewFactory = (...args: any[]) => { this.proxyViewFactory = (...args: any[]) => {
if (!this._viewFactory) { if (!this._viewFactory) {
throw new BaseException( throw new Error(
`Illegal state: CompiledTemplate for ${stringify(this.compType)} is not compiled yet!`); `Illegal state: CompiledTemplate for ${stringify(this.compType)} is not compiled yet!`);
} }
return this._viewFactory.apply(null, args); return this._viewFactory.apply(null, args);
@ -355,7 +352,7 @@ class CompiledTemplate {
get normalizedCompMeta(): CompileDirectiveMetadata { get normalizedCompMeta(): CompileDirectiveMetadata {
if (this.loading) { 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; return this._normalizedCompMeta;
} }
@ -370,7 +367,7 @@ class CompiledTemplate {
function assertComponent(meta: CompileDirectiveMetadata) { function assertComponent(meta: CompileDirectiveMetadata) {
if (!meta.isComponent) { 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.`);
} }
} }

View File

@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {BaseException} from '@angular/core';
import {ListWrapper} from './facade/collection'; import {ListWrapper} from './facade/collection';
import {StringWrapper, isBlank, isPresent} from './facade/lang'; import {StringWrapper, isBlank, isPresent} from './facade/lang';
@ -50,7 +49,7 @@ export class CssSelector {
while (isPresent(match = _SELECTOR_REGEXP.exec(selector))) { while (isPresent(match = _SELECTOR_REGEXP.exec(selector))) {
if (isPresent(match[1])) { if (isPresent(match[1])) {
if (inNot) { 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; inNot = true;
current = new CssSelector(); current = new CssSelector();
@ -71,7 +70,7 @@ export class CssSelector {
} }
if (isPresent(match[7])) { if (isPresent(match[7])) {
if (inNot) { 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); _addResult(results, cssSelector);
cssSelector = current = new CssSelector(); cssSelector = current = new CssSelector();

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license * 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 {Console, MAX_INTERPOLATION_VALUES} from '../../core_private';
import {CompileDirectiveMetadata, CompilePipeMetadata, CompileTokenMetadata, removeIdentifierDuplicates} from '../compile_metadata'; import {CompileDirectiveMetadata, CompilePipeMetadata, CompileTokenMetadata, removeIdentifierDuplicates} from '../compile_metadata';
@ -107,7 +107,7 @@ export class TemplateParser {
} }
if (errors.length > 0) { if (errors.length > 0) {
const errorString = errors.join('\n'); const errorString = errors.join('\n');
throw new BaseException(`Template parse errors:\n${errorString}`); throw new Error(`Template parse errors:\n${errorString}`);
} }
return result.templateAst; return result.templateAst;
@ -236,8 +236,7 @@ class TemplateParseVisitor implements html.Visitor {
this._checkPipes(ast, sourceSpan); this._checkPipes(ast, sourceSpan);
if (isPresent(ast) && if (isPresent(ast) &&
(<Interpolation>ast.ast).expressions.length > MAX_INTERPOLATION_VALUES) { (<Interpolation>ast.ast).expressions.length > MAX_INTERPOLATION_VALUES) {
throw new BaseException( throw new Error(`Only support at most ${MAX_INTERPOLATION_VALUES} interpolation values!`);
`Only support at most ${MAX_INTERPOLATION_VALUES} interpolation values!`);
} }
return ast; return ast;
} catch (e) { } catch (e) {

View File

@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license * 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 {CompileDiDependencyMetadata, CompileDirectiveMetadata, CompileIdentifierMap, CompileIdentifierMetadata, CompileProviderMetadata, CompileQueryMetadata, CompileTokenMetadata} from '../compile_metadata';
import {ListWrapper, StringMapWrapper} from '../facade/collection'; import {ListWrapper, StringMapWrapper} from '../facade/collection';

View File

@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {BaseException} from '@angular/core';
import {CompilePipeMetadata} from '../compile_metadata'; import {CompilePipeMetadata} from '../compile_metadata';
import {isBlank, isPresent} from '../facade/lang'; import {isBlank, isPresent} from '../facade/lang';
@ -86,7 +85,7 @@ function _findPipeMeta(view: CompileView, name: string): CompilePipeMetadata {
} }
} }
if (isBlank(pipeMeta)) { if (isBlank(pipeMeta)) {
throw new BaseException( throw new Error(
`Illegal state: Could not find pipe ${name} although the parser should have detected this error!`); `Illegal state: Could not find pipe ${name} although the parser should have detected this error!`);
} }
return pipeMeta; return pipeMeta;

View File

@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {BaseException} from '@angular/core';
import * as cdAst from '../expression_parser/ast'; import * as cdAst from '../expression_parser/ast';
import {isArray, isBlank, isPresent} from '../facade/lang'; import {isArray, isBlank, isPresent} from '../facade/lang';
@ -67,13 +66,13 @@ enum _Mode {
function ensureStatementMode(mode: _Mode, ast: cdAst.AST) { function ensureStatementMode(mode: _Mode, ast: cdAst.AST) {
if (mode !== _Mode.Statement) { 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) { function ensureExpressionMode(mode: _Mode, ast: cdAst.AST) {
if (mode !== _Mode.Expression) { 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; op = o.BinaryOperator.BiggerEquals;
break; break;
default: default:
throw new BaseException(`Unsupported operation ${ast.operation}`); throw new Error(`Unsupported operation ${ast.operation}`);
} }
return convertToStatementIfNeeded( return convertToStatementIfNeeded(
@ -273,7 +272,7 @@ class _AstToIrVisitor implements cdAst.AstVisitor {
if (receiver === this._implicitReceiver) { if (receiver === this._implicitReceiver) {
var varExpr = this._nameResolver.getLocal(ast.name); var varExpr = this._nameResolver.getLocal(ast.name);
if (isPresent(varExpr)) { 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( 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)); } visitAll(asts: cdAst.AST[], mode: _Mode): any { return asts.map(ast => this.visit(ast, mode)); }
visitQuote(ast: cdAst.Quote, mode: _Mode): any { 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 { private visit(ast: cdAst.AST, mode: _Mode): any {
@ -466,7 +465,7 @@ class _AstToIrVisitor implements cdAst.AstVisitor {
private releaseTemporary(temporary: o.ReadVarExpr) { private releaseTemporary(temporary: o.ReadVarExpr) {
this._currentTemporary--; this._currentTemporary--;
if (temporary.name != temporaryName(this.bindingIndex, 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`);
} }
} }
} }

View File

@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {BaseException} from '@angular/core';
import {CompileDirectiveMetadata, CompileTokenMetadata} from '../compile_metadata'; import {CompileDirectiveMetadata, CompileTokenMetadata} from '../compile_metadata';
import {isBlank, isPresent} from '../facade/lang'; import {isBlank, isPresent} from '../facade/lang';
@ -28,7 +27,7 @@ export function getPropertyInView(
viewProp = viewProp.prop('parent'); viewProp = viewProp.prop('parent');
} }
if (currView !== definedView) { if (currView !== definedView) {
throw new BaseException( throw new Error(
`Internal error: Could not calculate a property in a parent view: ${property}`); `Internal error: Could not calculate a property in a parent view: ${property}`);
} }
if (property instanceof o.ReadPropExpr) { if (property instanceof o.ReadPropExpr) {
@ -86,7 +85,7 @@ export function createPureProxy(
var pureProxyId = var pureProxyId =
argCount < Identifiers.pureProxies.length ? Identifiers.pureProxies[argCount] : null; argCount < Identifiers.pureProxies.length ? Identifiers.pureProxies[argCount] : null;
if (isBlank(pureProxyId)) { 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( view.createMethod.addStmt(
o.THIS_EXPR.prop(pureProxyProp.name).set(o.importExpr(pureProxyId).callFn([fn])).toStmt()); o.THIS_EXPR.prop(pureProxyProp.name).set(o.importExpr(pureProxyId).callFn([fn])).toStmt());

View File

@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license * 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 {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'; 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 output = parse(css);
var errors = output.errors; var errors = output.errors;
if (errors.length > 0) { 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; return output.ast;
} }

View File

@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license * 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 {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'; 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 output = new CssParser().parse(cssCode, 'some-fake-css-file.css');
var errors = output.errors; var errors = output.errors;
if (errors.length > 0 && !ignoreErrors) { 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; return output.ast;
} }

View File

@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {BaseException} from '@angular/core';
import * as html from '../../src/ml_parser/ast'; import * as html from '../../src/ml_parser/ast';
import {ParseTreeResult} from '../../src/ml_parser/html_parser'; import {ParseTreeResult} from '../../src/ml_parser/html_parser';
import {ParseLocation} from '../../src/parse_util'; 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[] { export function humanizeDom(parseResult: ParseTreeResult, addSourceSpan: boolean = false): any[] {
if (parseResult.errors.length > 0) { if (parseResult.errors.length > 0) {
var errorString = parseResult.errors.join('\n'); 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); return humanizeNodes(parseResult.rootNodes, addSourceSpan);

View File

@ -9,13 +9,12 @@
// ATTENTION: This file will be overwritten with generated code by main() // ATTENTION: This file will be overwritten with generated code by main()
import * as o from '@angular/compiler/src/output/output_ast'; import * as o from '@angular/compiler/src/output/output_ast';
import {TypeScriptEmitter} from '@angular/compiler/src/output/ts_emitter'; import {TypeScriptEmitter} from '@angular/compiler/src/output/ts_emitter';
import {BaseException} from '@angular/core';
import {print} from '../../src/facade/lang'; import {print} from '../../src/facade/lang';
import {assetUrl} from '../../src/util'; import {assetUrl} from '../../src/util';
function unimplemented(): any { function unimplemented(): any {
throw new BaseException('unimplemented'); throw new Error('unimplemented');
} }
import {SimpleJsImportGenerator, codegenExportsVars, codegenStmts} from './output_emitter_util'; import {SimpleJsImportGenerator, codegenExportsVars, codegenStmts} from './output_emitter_util';

View File

@ -8,7 +8,6 @@
// ATTENTION: This file will be overwritten with generated code by main() // ATTENTION: This file will be overwritten with generated code by main()
import {JavaScriptEmitter} from '@angular/compiler/src/output/js_emitter'; import {JavaScriptEmitter} from '@angular/compiler/src/output/js_emitter';
import {BaseException} from '@angular/core';
import {print} from '../../src/facade/lang'; import {print} from '../../src/facade/lang';
import {assetUrl} from '../../src/util'; import {assetUrl} from '../../src/util';
@ -16,7 +15,7 @@ import {assetUrl} from '../../src/util';
import {SimpleJsImportGenerator, codegenExportsVars, codegenStmts} from './output_emitter_util'; import {SimpleJsImportGenerator, codegenExportsVars, codegenStmts} from './output_emitter_util';
export function getExpressions(): any { export function getExpressions(): any {
throw new BaseException('unimplemented'); throw new Error('unimplemented');
} }
// Generator // Generator

View File

@ -8,7 +8,7 @@
import {interpretStatements} from '@angular/compiler/src/output/output_interpreter'; import {interpretStatements} from '@angular/compiler/src/output/output_interpreter';
import {jitStatements} from '@angular/compiler/src/output/output_jit'; 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 {ViewType} from '@angular/core/src/linker/view_type';
import {beforeEach, ddescribe, describe, iit, inject, it, xit} from '@angular/core/testing/testing_internal'; import {beforeEach, ddescribe, describe, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter'; import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
@ -179,7 +179,7 @@ export function main() {
() => { expect(expressions['throwError']).toThrowError('someError'); }); () => { expect(expressions['throwError']).toThrowError('someError'); });
it('should support catching errors', () => { it('should support catching errors', () => {
function someOperation() { throw new BaseException('Boom!'); } function someOperation() { throw new Error('Boom!'); }
var errorAndStack = expressions['catchError'](someOperation); var errorAndStack = expressions['catchError'](someOperation);
expect(errorAndStack[0].message).toEqual('Boom!'); expect(errorAndStack[0].message).toEqual('Boom!');

View File

@ -10,7 +10,8 @@ import {CompileIdentifierMetadata} from '@angular/compiler/src/compile_metadata'
import * as o from '@angular/compiler/src/output/output_ast'; import * as o from '@angular/compiler/src/output/output_ast';
import {ImportGenerator} from '@angular/compiler/src/output/path_util'; import {ImportGenerator} from '@angular/compiler/src/output/path_util';
import {assetUrl} from '@angular/compiler/src/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'; import {ViewType} from '@angular/core/src/linker/view_type';
export class ExternalClass { export class ExternalClass {
@ -34,8 +35,8 @@ var enumIdentifier = new CompileIdentifierMetadata({
runtime: ViewType.HOST runtime: ViewType.HOST
}); });
var baseExceptionIdentifier = new CompileIdentifierMetadata( var baseErrorIdentifier = new CompileIdentifierMetadata(
{name: 'BaseException', moduleUrl: assetUrl('core'), runtime: BaseException}); {name: 'BaseError', moduleUrl: assetUrl('core', 'facade/errors'), runtime: BaseError});
export var codegenExportsVars = [ export var codegenExportsVars = [
'getExpressions', 'getExpressions',
@ -68,8 +69,8 @@ var _getExpressionsStmts: o.Statement[] = [
.toDeclStmt(), .toDeclStmt(),
o.variable('throwError') o.variable('throwError')
.set(o.fn([], [new o.ThrowStmt(o.importExpr(baseExceptionIdentifier).instantiate([o.literal( .set(o.fn([], [new o.ThrowStmt(
'someError')]))])) o.importExpr(baseErrorIdentifier).instantiate([o.literal('someError')]))]))
.toDeclStmt(), .toDeclStmt(),
o.variable('catchError') o.variable('catchError')

View File

@ -7,7 +7,6 @@
*/ */
import {MetadataOverride} from '@angular/core/testing'; import {MetadataOverride} from '@angular/core/testing';
import {BaseException} from '../src/facade/exceptions';
import {stringify} from '../src/facade/lang'; import {stringify} from '../src/facade/lang';
type StringMap = { type StringMap = {
@ -31,8 +30,7 @@ export class MetadataOverrider {
if (override.set) { if (override.set) {
if (override.remove || override.add) { if (override.remove || override.add) {
throw new BaseException( throw new Error(`Cannot set and add/remove ${stringify(metadataClass)} at the same time!`);
`Cannot set and add/remove ${stringify(metadataClass)} at the same time!`);
} }
setMetadata(props, override.set); setMetadata(props, override.set);
} }

View File

@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {BaseException} from '@angular/core';
import {ResourceLoader} from '../index'; import {ResourceLoader} from '../index';
import {ListWrapper, Map} from '../src/facade/collection'; import {ListWrapper, Map} from '../src/facade/collection';
@ -54,7 +53,7 @@ export class MockResourceLoader extends ResourceLoader {
*/ */
flush() { flush() {
if (this._requests.length === 0) { if (this._requests.length === 0) {
throw new BaseException('No pending requests to flush'); throw new Error('No pending requests to flush');
} }
do { do {
@ -76,7 +75,7 @@ export class MockResourceLoader extends ResourceLoader {
urls.push(expectation.url); urls.push(expectation.url);
} }
throw new BaseException(`Unsatisfied requests: ${urls.join(', ')}`); throw new Error(`Unsatisfied requests: ${urls.join(', ')}`);
} }
private _processRequest(request: _PendingRequest) { private _processRequest(request: _PendingRequest) {
@ -97,7 +96,7 @@ export class MockResourceLoader extends ResourceLoader {
return; return;
} }
throw new BaseException(`Unexpected request ${url}`); throw new Error(`Unexpected request ${url}`);
} }
} }

View File

@ -30,7 +30,7 @@ export {wtfCreateScope, wtfLeave, wtfStartTimeRange, wtfEndTimeRange, WtfScopeFn
export {Type} from './src/type'; export {Type} from './src/type';
export {EventEmitter} from './src/facade/async'; 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 './private_export';
export * from './src/animation/metadata'; export * from './src/animation/metadata';

View File

@ -20,6 +20,7 @@ import * as console from './src/console';
import * as debug from './src/debug/debug_renderer'; import * as debug from './src/debug/debug_renderer';
import * as provider from './src/di/provider'; import * as provider from './src/di/provider';
import * as reflective_provider from './src/di/reflective_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 component_factory_resolver from './src/linker/component_factory_resolver';
import * as debug_context from './src/linker/debug_context'; import * as debug_context from './src/linker/debug_context';
import * as element from './src/linker/element'; 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 security from './src/security';
import * as decorators from './src/util/decorators'; import * as decorators from './src/util/decorators';
// These generic types can't be exported within the __core_private_types__ // These generic types can't be exported within the __core_private_types__
// interface because the generic type info will be lost. So just exporting // interface because the generic type info will be lost. So just exporting
// them separately. // them separately.
@ -110,6 +112,7 @@ export interface __core_private_types__ {
DEFAULT_STATE: typeof DEFAULT_STATE_; DEFAULT_STATE: typeof DEFAULT_STATE_;
EMPTY_STATE: typeof EMPTY_STATE_; EMPTY_STATE: typeof EMPTY_STATE_;
FILL_STYLE_FLAG: typeof FILL_STYLE_FLAG_; FILL_STYLE_FLAG: typeof FILL_STYLE_FLAG_;
ComponentStillLoadingError: typeof ComponentStillLoadingError;
} }
export var __core_private__ = { export var __core_private__ = {
@ -176,5 +179,6 @@ export var __core_private__ = {
ANY_STATE: ANY_STATE_, ANY_STATE: ANY_STATE_,
DEFAULT_STATE: DEFAULT_STATE_, DEFAULT_STATE: DEFAULT_STATE_,
EMPTY_STATE: EMPTY_STATE_, EMPTY_STATE: EMPTY_STATE_,
FILL_STYLE_FLAG: FILL_STYLE_FLAG_ FILL_STYLE_FLAG: FILL_STYLE_FLAG_,
ComponentStillLoadingError: ComponentStillLoadingError
}; };

View File

@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {BaseException} from '../facade/exceptions';
import {scheduleMicroTask} from '../facade/lang'; import {scheduleMicroTask} from '../facade/lang';
@ -26,10 +25,8 @@ export abstract class AnimationPlayer {
abstract reset(): void; abstract reset(): void;
abstract setPosition(p: any /** TODO #9100 */): void; abstract setPosition(p: any /** TODO #9100 */): void;
abstract getPosition(): number; abstract getPosition(): number;
get parentPlayer(): AnimationPlayer { throw new BaseException('NOT IMPLEMENTED: Base Class'); } get parentPlayer(): AnimationPlayer { throw new Error('NOT IMPLEMENTED: Base Class'); }
set parentPlayer(player: AnimationPlayer) { set parentPlayer(player: AnimationPlayer) { throw new Error('NOT IMPLEMENTED: Base Class'); }
throw new BaseException('NOT IMPLEMENTED: Base Class');
}
} }
export class NoOpAnimationPlayer implements AnimationPlayer { export class NoOpAnimationPlayer implements AnimationPlayer {

View File

@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {BaseException} from '../facade/exceptions';
import {NumberWrapper, isArray, isPresent, isString} from '../facade/lang'; import {NumberWrapper, isArray, isPresent, isString} from '../facade/lang';
/** /**
@ -102,7 +101,7 @@ export class AnimationAnimateMetadata extends AnimationMetadata {
*/ */
export abstract class AnimationWithStepsMetadata extends AnimationMetadata { export abstract class AnimationWithStepsMetadata extends AnimationMetadata {
constructor() { super(); } constructor() { super(); }
get steps(): AnimationMetadata[] { throw new BaseException('NOT IMPLEMENTED: Base Class'); } get steps(): AnimationMetadata[] { throw new Error('NOT IMPLEMENTED: Base Class'); }
} }
/** /**

View File

@ -6,8 +6,9 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {ErrorHandler} from '../src/error_handler';
import {ListWrapper} from '../src/facade/collection'; 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 {isBlank, isPresent, isPromise, stringify} from '../src/facade/lang';
import {ApplicationInitStatus} from './application_init'; import {ApplicationInitStatus} from './application_init';
@ -40,8 +41,7 @@ var _platform: PlatformRef;
*/ */
export function enableProdMode(): void { export function enableProdMode(): void {
if (_runModeLocked) { if (_runModeLocked) {
// Cannot use BaseException as that ends up importing from facade/lang. throw new Error('Cannot enable prod mode after platform setup.');
throw new BaseException('Cannot enable prod mode after platform setup.');
} }
_devMode = false; _devMode = false;
} }
@ -67,7 +67,7 @@ export function isDevMode(): boolean {
*/ */
export function createPlatform(injector: Injector): PlatformRef { export function createPlatform(injector: Injector): PlatformRef {
if (isPresent(_platform) && !_platform.destroyed) { 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.'); 'There can be only one platform. Destroy the previous one to create a new one.');
} }
_platform = injector.get(PlatformRef); _platform = injector.get(PlatformRef);
@ -115,10 +115,10 @@ export function createPlatformFactory(
export function assertPlatform(requiredToken: any): PlatformRef { export function assertPlatform(requiredToken: any): PlatformRef {
var platform = getPlatform(); var platform = getPlatform();
if (isBlank(platform)) { if (isBlank(platform)) {
throw new BaseException('No platform exists!'); throw new Error('No platform exists!');
} }
if (isPresent(platform) && isBlank(platform.injector.get(requiredToken, null))) { 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.'); 'A platform with a different configuration has been created. Please destroy it first.');
} }
return platform; return platform;
@ -221,13 +221,12 @@ export abstract class PlatformRef {
get destroyed(): boolean { throw unimplemented(); } get destroyed(): boolean { throw unimplemented(); }
} }
function _callAndReportToExceptionHandler( function _callAndReportToExceptionHandler(errorHandler: ErrorHandler, callback: () => any): any {
exceptionHandler: ExceptionHandler, callback: () => any): any {
try { try {
const result = callback(); const result = callback();
if (isPromise(result)) { if (isPromise(result)) {
return result.catch((e: any) => { return result.catch((e: any) => {
exceptionHandler.call(e); errorHandler.handleError(e);
// rethrow as the exception handler might not do it // rethrow as the exception handler might not do it
throw e; throw e;
}); });
@ -235,7 +234,7 @@ function _callAndReportToExceptionHandler(
return result; return result;
} }
} catch (e) { } catch (e) {
exceptionHandler.call(e); errorHandler.handleError(e);
// rethrow as the exception handler might not do it // rethrow as the exception handler might not do it
throw e; throw e;
} }
@ -258,7 +257,7 @@ export class PlatformRef_ extends PlatformRef {
destroy() { destroy() {
if (this._destroyed) { 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()); ListWrapper.clone(this._modules).forEach((app) => app.destroy());
this._destroyListeners.forEach((dispose) => dispose()); this._destroyListeners.forEach((dispose) => dispose());
@ -282,13 +281,12 @@ export class PlatformRef_ extends PlatformRef {
const ngZoneInjector = const ngZoneInjector =
ReflectiveInjector.resolveAndCreate([{provide: NgZone, useValue: ngZone}], this.injector); ReflectiveInjector.resolveAndCreate([{provide: NgZone, useValue: ngZone}], this.injector);
const moduleRef = <NgModuleInjector<M>>moduleFactory.create(ngZoneInjector); const moduleRef = <NgModuleInjector<M>>moduleFactory.create(ngZoneInjector);
const exceptionHandler: ExceptionHandler = moduleRef.injector.get(ExceptionHandler, null); const exceptionHandler: ErrorHandler = moduleRef.injector.get(ErrorHandler, null);
if (!exceptionHandler) { if (!exceptionHandler) {
throw new Error('No ExceptionHandler. Is platform module (BrowserModule) included?'); throw new Error('No ExceptionHandler. Is platform module (BrowserModule) included?');
} }
moduleRef.onDestroy(() => ListWrapper.remove(this._modules, moduleRef)); moduleRef.onDestroy(() => ListWrapper.remove(this._modules, moduleRef));
ngZone.onError.subscribe( ngZone.onError.subscribe({next: (error: any) => { exceptionHandler.handleError(error); }});
{next: (error: any) => { exceptionHandler.call(error, error ? error.stack : null); }});
return _callAndReportToExceptionHandler(exceptionHandler, () => { return _callAndReportToExceptionHandler(exceptionHandler, () => {
const initStatus: ApplicationInitStatus = moduleRef.injector.get(ApplicationInitStatus); const initStatus: ApplicationInitStatus = moduleRef.injector.get(ApplicationInitStatus);
return initStatus.donePromise.then(() => { return initStatus.donePromise.then(() => {
@ -333,7 +331,7 @@ export class PlatformRef_ extends PlatformRef {
} else if (moduleRef.instance.ngDoBootstrap) { } else if (moduleRef.instance.ngDoBootstrap) {
moduleRef.instance.ngDoBootstrap(appRef); moduleRef.instance.ngDoBootstrap(appRef);
} else { } 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. ` + `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.`); `Please define one of these.`);
} }
@ -400,7 +398,7 @@ export class ApplicationRef_ extends ApplicationRef {
constructor( constructor(
private _zone: NgZone, private _console: Console, private _injector: Injector, private _zone: NgZone, private _console: Console, private _injector: Injector,
private _exceptionHandler: ExceptionHandler, private _exceptionHandler: ErrorHandler,
private _componentFactoryResolver: ComponentFactoryResolver, private _componentFactoryResolver: ComponentFactoryResolver,
private _initStatus: ApplicationInitStatus, private _initStatus: ApplicationInitStatus,
@Optional() private _testabilityRegistry: TestabilityRegistry, @Optional() private _testabilityRegistry: TestabilityRegistry,
@ -422,7 +420,7 @@ export class ApplicationRef_ extends ApplicationRef {
bootstrap<C>(componentOrFactory: ComponentFactory<C>|Type<C>): ComponentRef<C> { bootstrap<C>(componentOrFactory: ComponentFactory<C>|Type<C>): ComponentRef<C> {
if (!this._initStatus.done) { 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.'); 'Cannot bootstrap as there are still asynchronous initializers running. Bootstrap components in the `ngDoBootstrap` method of the root module.');
} }
let componentFactory: ComponentFactory<C>; let componentFactory: ComponentFactory<C>;
@ -471,7 +469,7 @@ export class ApplicationRef_ extends ApplicationRef {
tick(): void { tick(): void {
if (this._runningTick) { if (this._runningTick) {
throw new BaseException('ApplicationRef.tick is called recursively'); throw new Error('ApplicationRef.tick is called recursively');
} }
var s = ApplicationRef_._tickScope(); var s = ApplicationRef_._tickScope();

View File

@ -7,7 +7,6 @@
*/ */
import {isListLikeIterable, iterateListLike} from '../../facade/collection'; import {isListLikeIterable, iterateListLike} from '../../facade/collection';
import {BaseException} from '../../facade/exceptions';
import {getMapKey, isArray, isBlank, isPresent, looseIdentical, stringify} from '../../facade/lang'; import {getMapKey, isArray, isBlank, isPresent, looseIdentical, stringify} from '../../facade/lang';
import {ChangeDetectorRef} from '../change_detector_ref'; import {ChangeDetectorRef} from '../change_detector_ref';
@ -150,7 +149,7 @@ export class DefaultIterableDiffer implements IterableDiffer {
diff(collection: any): DefaultIterableDiffer { diff(collection: any): DefaultIterableDiffer {
if (isBlank(collection)) collection = []; if (isBlank(collection)) collection = [];
if (!isListLikeIterable(collection)) { if (!isListLikeIterable(collection)) {
throw new BaseException(`Error trying to diff '${collection}'`); throw new Error(`Error trying to diff '${collection}'`);
} }
if (this.check(collection)) { if (this.check(collection)) {

View File

@ -7,7 +7,6 @@
*/ */
import {StringMapWrapper} from '../../facade/collection'; import {StringMapWrapper} from '../../facade/collection';
import {BaseException} from '../../facade/exceptions';
import {isJsObject, looseIdentical, stringify} from '../../facade/lang'; import {isJsObject, looseIdentical, stringify} from '../../facade/lang';
import {ChangeDetectorRef} from '../change_detector_ref'; import {ChangeDetectorRef} from '../change_detector_ref';
@ -76,7 +75,7 @@ export class DefaultKeyValueDiffer implements KeyValueDiffer {
if (!map) { if (!map) {
map = new Map(); map = new Map();
} else if (!(map instanceof Map || isJsObject(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; return this.check(map) ? this : null;

View File

@ -8,7 +8,6 @@
import {OptionalMetadata, Provider, SkipSelfMetadata} from '../../di'; import {OptionalMetadata, Provider, SkipSelfMetadata} from '../../di';
import {ListWrapper} from '../../facade/collection'; import {ListWrapper} from '../../facade/collection';
import {BaseException} from '../../facade/exceptions';
import {getTypeNameForDebugging, isBlank, isPresent} from '../../facade/lang'; import {getTypeNameForDebugging, isBlank, isPresent} from '../../facade/lang';
import {ChangeDetectorRef} from '../change_detector_ref'; import {ChangeDetectorRef} from '../change_detector_ref';
@ -87,7 +86,7 @@ export class IterableDiffers {
// Typically would occur when calling IterableDiffers.extend inside of dependencies passed // Typically would occur when calling IterableDiffers.extend inside of dependencies passed
// to // to
// bootstrap(), which would override default pipes instead of extending them. // 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); return IterableDiffers.create(factories, parent);
}, },
@ -101,7 +100,7 @@ export class IterableDiffers {
if (isPresent(factory)) { if (isPresent(factory)) {
return factory; return factory;
} else { } else {
throw new BaseException( throw new Error(
`Cannot find a differ supporting object '${iterable}' of type '${getTypeNameForDebugging(iterable)}'`); `Cannot find a differ supporting object '${iterable}' of type '${getTypeNameForDebugging(iterable)}'`);
} }
} }

View File

@ -8,7 +8,6 @@
import {OptionalMetadata, Provider, SkipSelfMetadata} from '../../di'; import {OptionalMetadata, Provider, SkipSelfMetadata} from '../../di';
import {ListWrapper} from '../../facade/collection'; import {ListWrapper} from '../../facade/collection';
import {BaseException} from '../../facade/exceptions';
import {isBlank, isPresent} from '../../facade/lang'; import {isBlank, isPresent} from '../../facade/lang';
import {ChangeDetectorRef} from '../change_detector_ref'; import {ChangeDetectorRef} from '../change_detector_ref';
@ -77,7 +76,7 @@ export class KeyValueDiffers {
// Typically would occur when calling KeyValueDiffers.extend inside of dependencies passed // Typically would occur when calling KeyValueDiffers.extend inside of dependencies passed
// to // to
// bootstrap(), which would override default pipes instead of extending them. // 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); return KeyValueDiffers.create(factories, parent);
}, },
@ -91,7 +90,7 @@ export class KeyValueDiffers {
if (isPresent(factory)) { if (isPresent(factory)) {
return factory; return factory;
} else { } else {
throw new BaseException(`Cannot find a differ supporting object '${kv}'`); throw new Error(`Cannot find a differ supporting object '${kv}'`);
} }
} }
} }

View File

@ -25,5 +25,4 @@ export {ReflectiveInjector} from './di/reflective_injector';
export {Provider, TypeProvider, ValueProvider, ClassProvider, ExistingProvider, FactoryProvider} from './di/provider'; export {Provider, TypeProvider, ValueProvider, ClassProvider, ExistingProvider, FactoryProvider} from './di/provider';
export {ResolvedReflectiveFactory, ResolvedReflectiveProvider} from './di/reflective_provider'; export {ResolvedReflectiveFactory, ResolvedReflectiveProvider} from './di/reflective_provider';
export {ReflectiveKey} from './di/reflective_key'; export {ReflectiveKey} from './di/reflective_key';
export {NoProviderError, AbstractProviderError, CyclicDependencyError, InstantiationError, InvalidProviderError, NoAnnotationError, OutOfBoundsError} from './di/reflective_exceptions';
export {OpaqueToken} from './di/opaque_token'; export {OpaqueToken} from './di/opaque_token';

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license * 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'; import {stringify} from '../facade/lang';
const _THROW_IF_NOT_FOUND = new Object(); 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 { class _NullInjector implements Injector {
get(token: any, notFoundValue: any = _THROW_IF_NOT_FOUND): any { get(token: any, notFoundValue: any = _THROW_IF_NOT_FOUND): any {
if (notFoundValue === _THROW_IF_NOT_FOUND) { if (notFoundValue === _THROW_IF_NOT_FOUND) {
throw new BaseException(`No provider for ${stringify(token)}!`); throw new Error(`No provider for ${stringify(token)}!`);
} }
return notFoundValue; return notFoundValue;
} }

View File

@ -7,9 +7,10 @@
*/ */
import {ListWrapper} from '../facade/collection'; import {ListWrapper} from '../facade/collection';
import {BaseException, WrappedException} from '../facade/exceptions'; import {BaseError, WrappedError} from '../facade/errors';
import {isBlank, stringify} from '../facade/lang'; import {isBlank, stringify} from '../facade/lang';
import {Type} from '../type'; import {Type} from '../type';
import {ReflectiveInjector} from './reflective_injector'; import {ReflectiveInjector} from './reflective_injector';
import {ReflectiveKey} from './reflective_key'; import {ReflectiveKey} from './reflective_key';
@ -40,7 +41,7 @@ function constructResolvingPath(keys: any[]): string {
* Base class for all errors arising from misconfigured providers. * Base class for all errors arising from misconfigured providers.
* @stable * @stable
*/ */
export class AbstractProviderError extends BaseException { export class AbstractProviderError extends BaseError {
/** @internal */ /** @internal */
message: string; message: string;
@ -55,7 +56,7 @@ export class AbstractProviderError extends BaseException {
constructor( constructor(
injector: ReflectiveInjector, key: ReflectiveKey, constructResolvingMessage: Function) { injector: ReflectiveInjector, key: ReflectiveKey, constructResolvingMessage: Function) {
super('DI Exception'); super('DI Error');
this.keys = [key]; this.keys = [key];
this.injectors = [injector]; this.injectors = [injector];
this.constructResolvingMessage = constructResolvingMessage; this.constructResolvingMessage = constructResolvingMessage;
@ -147,7 +148,7 @@ export class CyclicDependencyError extends AbstractProviderError {
* ``` * ```
* @stable * @stable
*/ */
export class InstantiationError extends WrappedException { export class InstantiationError extends WrappedError {
/** @internal */ /** @internal */
keys: ReflectiveKey[]; keys: ReflectiveKey[];
@ -157,7 +158,7 @@ export class InstantiationError extends WrappedException {
constructor( constructor(
injector: ReflectiveInjector, originalException: any, originalStack: any, injector: ReflectiveInjector, originalException: any, originalStack: any,
key: ReflectiveKey) { key: ReflectiveKey) {
super('DI Exception', originalException, originalStack, null); super('DI Error', originalException);
this.keys = [key]; this.keys = [key];
this.injectors = [injector]; this.injectors = [injector];
} }
@ -167,9 +168,9 @@ export class InstantiationError extends WrappedException {
this.keys.push(key); this.keys.push(key);
} }
get wrapperMessage(): string { get message(): string {
var first = stringify(ListWrapper.first(this.keys).token); 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]; } get causeKey(): ReflectiveKey { return this.keys[0]; }
@ -188,7 +189,7 @@ export class InstantiationError extends WrappedException {
* ``` * ```
* @stable * @stable
*/ */
export class InvalidProviderError extends BaseException { export class InvalidProviderError extends BaseError {
constructor(provider: any) { constructor(provider: any) {
super(`Invalid provider - only instances of Provider and Type are allowed, got: ${provider}`); super(`Invalid provider - only instances of Provider and Type are allowed, got: ${provider}`);
} }
@ -223,7 +224,7 @@ export class InvalidProviderError extends BaseException {
* ``` * ```
* @stable * @stable
*/ */
export class NoAnnotationError extends BaseException { export class NoAnnotationError extends BaseError {
constructor(typeOrFunc: Type<any>|Function, params: any[][]) { constructor(typeOrFunc: Type<any>|Function, params: any[][]) {
super(NoAnnotationError._genMessage(typeOrFunc, params)); super(NoAnnotationError._genMessage(typeOrFunc, params));
} }
@ -259,7 +260,7 @@ export class NoAnnotationError extends BaseException {
* ``` * ```
* @stable * @stable
*/ */
export class OutOfBoundsError extends BaseException { export class OutOfBoundsError extends BaseError {
constructor(index: number) { super(`Index ${index} is out-of-bounds.`); } constructor(index: number) { super(`Index ${index} is out-of-bounds.`); }
} }
@ -276,7 +277,7 @@ export class OutOfBoundsError extends BaseException {
* ])).toThrowError(); * ])).toThrowError();
* ``` * ```
*/ */
export class MixingMultiProvidersWithRegularProvidersError extends BaseException { export class MixingMultiProvidersWithRegularProvidersError extends BaseError {
constructor(provider1: any, provider2: any) { constructor(provider1: any, provider2: any) {
super( super(
'Cannot mix multi providers and regular providers, got: ' + provider1.toString() + ' ' + 'Cannot mix multi providers and regular providers, got: ' + provider1.toString() + ' ' +

View File

@ -7,13 +7,13 @@
*/ */
import {ListWrapper} from '../facade/collection'; import {ListWrapper} from '../facade/collection';
import {BaseException, unimplemented} from '../facade/exceptions'; import {unimplemented} from '../facade/errors';
import {Type} from '../type'; import {Type} from '../type';
import {Injector, THROW_IF_NOT_FOUND} from './injector'; import {Injector, THROW_IF_NOT_FOUND} from './injector';
import {SelfMetadata, SkipSelfMetadata} from './metadata'; import {SelfMetadata, SkipSelfMetadata} from './metadata';
import {Provider} from './provider'; 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 {ReflectiveKey} from './reflective_key';
import {ReflectiveDependency, ResolvedReflectiveFactory, ResolvedReflectiveProvider, resolveReflectiveProviders} from './reflective_provider'; import {ReflectiveDependency, ResolvedReflectiveFactory, ResolvedReflectiveProvider, resolveReflectiveProviders} from './reflective_provider';
@ -797,7 +797,7 @@ export class ReflectiveInjector_ implements ReflectiveInjector {
d19); d19);
break; break;
default: default:
throw new BaseException( throw new Error(
`Cannot instantiate '${provider.key.displayName}' because it has more than 20 dependencies`); `Cannot instantiate '${provider.key.displayName}' because it has more than 20 dependencies`);
} }
} catch (e) { } catch (e) {

View File

@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {BaseException} from '../facade/exceptions';
import {isBlank, stringify} from '../facade/lang'; import {isBlank, stringify} from '../facade/lang';
import {resolveForwardRef} from './forward_ref'; import {resolveForwardRef} from './forward_ref';
@ -34,7 +33,7 @@ export class ReflectiveKey {
*/ */
constructor(public token: Object, public id: number) { constructor(public token: Object, public id: number) {
if (isBlank(token)) { if (isBlank(token)) {
throw new BaseException('Token must be defined!'); throw new Error('Token must be defined!');
} }
} }

View File

@ -14,7 +14,7 @@ import {Type} from '../type';
import {resolveForwardRef} from './forward_ref'; import {resolveForwardRef} from './forward_ref';
import {DependencyMetadata, HostMetadata, InjectMetadata, OptionalMetadata, SelfMetadata, SkipSelfMetadata} from './metadata'; import {DependencyMetadata, HostMetadata, InjectMetadata, OptionalMetadata, SelfMetadata, SkipSelfMetadata} from './metadata';
import {ClassProvider, ExistingProvider, FactoryProvider, Provider, TypeProvider, ValueProvider} from './provider'; 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'; import {ReflectiveKey} from './reflective_key';

View File

@ -6,22 +6,12 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {BaseWrappedException} from './base_wrapped_exception'; import {WrappedError} from './facade/errors';
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(){};
}
/** /**
* Provides a hook for centralized exception handling. * 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, * intercept error handling,
* write a custom exception handler that replaces this default as appropriate for your app. * write a custom exception handler that replaces this default as appropriate for your app.
* *
@ -29,112 +19,88 @@ class _ArrayLogger {
* *
* ```javascript * ```javascript
* *
* class MyExceptionHandler implements ExceptionHandler { * class MyExceptionHandler implements ErrorHandler {
* call(error, stackTrace = null, reason = null) { * call(error, stackTrace = null, reason = null) {
* // do something with the exception * // do something with the exception
* } * }
* } * }
* *
* @NgModule({ * @NgModule({
* providers: [{provide: ExceptionHandler, useClass: MyExceptionHandler}] * providers: [{provide: ErrorHandler, useClass: MyErrorHandler}]
* }) * })
* class MyModule {} * class MyModule {}
* ``` * ```
* @stable * @stable
*/ */
export class ExceptionHandler { export class ErrorHandler {
constructor(private _logger: any, private _rethrowException: boolean = true) {} /**
* @internal
*/
_console: Console = console;
static exceptionToString(exception: any, stackTrace: any = null, reason: string = null): string { constructor(private rethrowError: boolean = true) {}
var l = new _ArrayLogger();
var e = new ExceptionHandler(l, false);
e.call(exception, stackTrace, reason);
return l.res.join('\n');
}
call(exception: any, stackTrace: any = null, reason: string = null): void { handleError(error: any): void {
var originalException = this._findOriginalException(exception); var originalError = this._findOriginalError(error);
var originalStack = this._findOriginalStack(exception); var originalStack = this._findOriginalStack(error);
var context = this._findContext(exception); var context = this._findContext(error);
this._logger.logGroup(`EXCEPTION: ${this._extractMessage(exception)}`); this._console.error(`EXCEPTION: ${this._extractMessage(error)}`);
if (isPresent(stackTrace) && isBlank(originalStack)) { if (originalError) {
this._logger.logError('STACKTRACE:'); this._console.error(`ORIGINAL EXCEPTION: ${this._extractMessage(originalError)}`);
this._logger.logError(this._longStackTrace(stackTrace));
} }
if (isPresent(reason)) { if (originalStack) {
this._logger.logError(`REASON: ${reason}`); this._console.error('ORIGINAL STACKTRACE:');
this._console.error(originalStack);
} }
if (isPresent(originalException)) { if (context) {
this._logger.logError(`ORIGINAL EXCEPTION: ${this._extractMessage(originalException)}`); 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 // 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. // when an error happens. If we do not rethrow, bootstrap will always succeed.
if (this._rethrowException) throw exception; if (this.rethrowError) throw error;
} }
/** @internal */ /** @internal */
_extractMessage(exception: any): string { _extractMessage(error: any): string {
return exception instanceof BaseWrappedException ? exception.wrapperMessage : return error instanceof Error ? error.message : error.toString();
exception.toString();
} }
/** @internal */ /** @internal */
_longStackTrace(stackTrace: any): any { _findContext(error: any): any {
return isListLikeIterable(stackTrace) ? (<any[]>stackTrace).join('\n\n-----async gap-----\n') : if (error) {
stackTrace.toString(); return error.context ? error.context :
} this._findContext((error as WrappedError).originalError);
} else {
/** @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.
return null; return null;
} }
} }
/** @internal */ /** @internal */
_findOriginalException(exception: any): any { _findOriginalError(error: any): any {
if (!(exception instanceof BaseWrappedException)) return null; var e = (error as WrappedError).originalError;
while (e && (e as WrappedError).originalError) {
var e = exception.originalException; e = (e as WrappedError).originalError;
while (e instanceof BaseWrappedException && isPresent(e.originalException)) {
e = e.originalException;
} }
return e; return e;
} }
/** @internal */ /** @internal */
_findOriginalStack(exception: any): any { _findOriginalStack(error: any): string {
if (!(exception instanceof BaseWrappedException)) return null; if (!(error instanceof Error)) return null;
var e = exception; var e: any = error;
var stack = exception.originalStack; var stack: string = e.stack;
while (e instanceof BaseWrappedException && isPresent(e.originalException)) { while (e instanceof Error && (e as WrappedError).originalError) {
e = e.originalException; e = (e as WrappedError).originalError;
if (e instanceof BaseWrappedException && isPresent(e.originalException)) { if (e instanceof Error && e.stack) {
stack = e.originalStack; stack = e.stack;
} }
} }

View File

@ -7,11 +7,10 @@
*/ */
// Public API for compiler // 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 {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 {ElementRef} from './linker/element_ref';
export {ExpressionChangedAfterItHasBeenCheckedException} from './linker/exceptions';
export {NgModuleFactory, NgModuleRef} from './linker/ng_module_factory'; export {NgModuleFactory, NgModuleRef} from './linker/ng_module_factory';
export {NgModuleFactoryLoader} from './linker/ng_module_factory_loader'; export {NgModuleFactoryLoader} from './linker/ng_module_factory_loader';
export {QueryList} from './linker/query_list'; export {QueryList} from './linker/query_list';

View File

@ -7,7 +7,7 @@
*/ */
import {OpaqueToken} from '../di'; import {OpaqueToken} from '../di';
import {BaseException} from '../facade/exceptions'; import {BaseError} from '../facade/errors';
import {stringify} from '../facade/lang'; import {stringify} from '../facade/lang';
import {ViewEncapsulation} from '../metadata'; import {ViewEncapsulation} from '../metadata';
import {Type} from '../type'; import {Type} from '../type';
@ -22,7 +22,7 @@ import {NgModuleFactory} from './ng_module_factory';
* *
* @stable * @stable
*/ */
export class ComponentStillLoadingError extends BaseException { export class ComponentStillLoadingError extends BaseError {
constructor(public compType: Type<any>) { constructor(public compType: Type<any>) {
super(`Can't compile synchronously as ${stringify(compType)} is still being loaded!`); super(`Can't compile synchronously as ${stringify(compType)} is still being loaded!`);
} }
@ -41,7 +41,7 @@ export class ModuleWithComponentFactories<T> {
function _throwError() { function _throwError() {
throw new BaseException(`Runtime compiler is not loaded`); throw new Error(`Runtime compiler is not loaded`);
} }
/** /**

View File

@ -8,7 +8,7 @@
import {ChangeDetectorRef} from '../change_detection/change_detection'; import {ChangeDetectorRef} from '../change_detection/change_detection';
import {Injector} from '../di/injector'; import {Injector} from '../di/injector';
import {unimplemented} from '../facade/exceptions'; import {unimplemented} from '../facade/errors';
import {isBlank} from '../facade/lang'; import {isBlank} from '../facade/lang';
import {Type} from '../type'; import {Type} from '../type';
import {AppElement} from './element'; import {AppElement} from './element';

View File

@ -6,17 +6,18 @@
* found in the LICENSE file at https://angular.io/license * 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 {stringify} from '../facade/lang';
import {Type} from '../type'; import {Type} from '../type';
import {ComponentFactory} from './component_factory'; import {ComponentFactory} from './component_factory';
/** /**
* @stable * @stable
*/ */
export class NoComponentFactoryError extends BaseException { export class NoComponentFactoryError extends BaseError {
constructor(public component: Function) { constructor(public component: Function) {
super(`No component factory found for ${stringify(component)}`); super(`No component factory found for ${stringify(component)}`);
} }

View File

@ -8,7 +8,6 @@
import {Injector} from '../di/injector'; import {Injector} from '../di/injector';
import {ListWrapper} from '../facade/collection'; import {ListWrapper} from '../facade/collection';
import {BaseException} from '../facade/exceptions';
import {isPresent} from '../facade/lang'; import {isPresent} from '../facade/lang';
import {ElementRef} from './element_ref'; import {ElementRef} from './element_ref';
@ -63,7 +62,7 @@ export class AppElement {
moveView(view: AppView<any>, currentIndex: number) { moveView(view: AppView<any>, currentIndex: number) {
var previousIndex = this.nestedViews.indexOf(view); var previousIndex = this.nestedViews.indexOf(view);
if (view.type === ViewType.COMPONENT) { 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; var nestedViews = this.nestedViews;
if (nestedViews == null) { if (nestedViews == null) {
@ -87,7 +86,7 @@ export class AppElement {
attachView(view: AppView<any>, viewIndex: number) { attachView(view: AppView<any>, viewIndex: number) {
if (view.type === ViewType.COMPONENT) { 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; var nestedViews = this.nestedViews;
if (nestedViews == null) { if (nestedViews == null) {
@ -111,7 +110,7 @@ export class AppElement {
detachView(viewIndex: number): AppView<any> { detachView(viewIndex: number): AppView<any> {
var view = ListWrapper.removeAt(this.nestedViews, viewIndex); var view = ListWrapper.removeAt(this.nestedViews, viewIndex);
if (view.type === ViewType.COMPONENT) { 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(); view.detach();

View File

@ -7,7 +7,10 @@
*/ */
import {UNINITIALIZED} from '../change_detection/change_detection_util'; 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) { * set prop(v) {
* // this updates the parent property, which is disallowed during change detection * // 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"; * this.parent.parentProp = "updated";
* } * }
* } * }
* ``` * ```
* @stable * @stable
*/ */
export class ExpressionChangedAfterItHasBeenCheckedException extends BaseException { export class ExpressionChangedAfterItHasBeenCheckedError extends BaseError {
constructor(oldValue: any, currValue: any, context: any) { constructor(oldValue: any, currValue: any) {
let msg = let msg =
`Expression has changed after it was checked. Previous value: '${oldValue}'. Current value: '${currValue}'.`; `Expression has changed after it was checked. Previous value: '${oldValue}'. Current value: '${currValue}'.`;
if (oldValue === UNINITIALIZED) { if (oldValue === UNINITIALIZED) {
@ -64,9 +67,15 @@ export class ExpressionChangedAfterItHasBeenCheckedException extends BaseExcepti
* be useful for debugging. * be useful for debugging.
* @stable * @stable
*/ */
export class ViewWrappedException extends WrappedException { export class ViewWrappedError extends WrappedError {
constructor(originalException: any, originalStack: any, context: any) { /**
super(`Error in ${context.source}`, originalException, originalStack, context); * 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. * This is an internal Angular error.
* @stable * @stable
*/ */
export class ViewDestroyedException extends BaseException { export class ViewDestroyedError extends BaseError {
constructor(details: string) { super(`Attempt to use a destroyed view: ${details}`); } constructor(details: string) { super(`Attempt to use a destroyed view: ${details}`); }
} }

View File

@ -7,7 +7,7 @@
*/ */
import {Injector, THROW_IF_NOT_FOUND} from '../di/injector'; 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 {stringify} from '../facade/lang';
import {Type} from '../type'; import {Type} from '../type';
import {ComponentFactory} from './component_factory'; import {ComponentFactory} from './component_factory';
@ -107,7 +107,7 @@ export abstract class NgModuleInjector<T> extends CodegenComponentFactoryResolve
destroy(): void { destroy(): void {
if (this._destroyed) { if (this._destroyed) {
throw new BaseException( throw new Error(
`The ng module ${stringify(this.instance.constructor)} has already been destroyed.`); `The ng module ${stringify(this.instance.constructor)} has already been destroyed.`);
} }
this._destroyed = true; this._destroyed = true;

View File

@ -21,7 +21,7 @@ import {RenderComponentType, RenderDebugInfo, Renderer} from '../render/api';
import {DebugContext, StaticNodeDebugInfo} from './debug_context'; import {DebugContext, StaticNodeDebugInfo} from './debug_context';
import {AppElement} from './element'; import {AppElement} from './element';
import {ElementInjector} from './element_injector'; import {ElementInjector} from './element_injector';
import {ExpressionChangedAfterItHasBeenCheckedException, ViewDestroyedException, ViewWrappedException} from './exceptions'; import {ExpressionChangedAfterItHasBeenCheckedError, ViewDestroyedError, ViewWrappedError} from './errors';
import {ViewRef_} from './view_ref'; import {ViewRef_} from './view_ref';
import {ViewType} from './view_type'; import {ViewType} from './view_type';
import {ViewUtils, ensureSlotCount, flattenNestedViewRenderNodes} from './view_utils'; import {ViewUtils, ensureSlotCount, flattenNestedViewRenderNodes} from './view_utils';
@ -357,7 +357,7 @@ export abstract class AppView<T> {
eventHandler(cb: Function): Function { return cb; } 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<T> extends AppView<T> { export class DebugAppView<T> extends AppView<T> {
@ -376,7 +376,7 @@ export class DebugAppView<T> extends AppView<T> {
try { try {
return super.create(context, givenProjectableNodes, rootSelectorOrNode); return super.create(context, givenProjectableNodes, rootSelectorOrNode);
} catch (e) { } catch (e) {
this._rethrowWithContext(e, e.stack); this._rethrowWithContext(e);
throw e; throw e;
} }
} }
@ -386,7 +386,7 @@ export class DebugAppView<T> extends AppView<T> {
try { try {
return super.injectorGet(token, nodeIndex, notFoundResult); return super.injectorGet(token, nodeIndex, notFoundResult);
} catch (e) { } catch (e) {
this._rethrowWithContext(e, e.stack); this._rethrowWithContext(e);
throw e; throw e;
} }
} }
@ -396,7 +396,7 @@ export class DebugAppView<T> extends AppView<T> {
try { try {
super.detach(); super.detach();
} catch (e) { } catch (e) {
this._rethrowWithContext(e, e.stack); this._rethrowWithContext(e);
throw e; throw e;
} }
} }
@ -406,7 +406,7 @@ export class DebugAppView<T> extends AppView<T> {
try { try {
super.destroyLocal(); super.destroyLocal();
} catch (e) { } catch (e) {
this._rethrowWithContext(e, e.stack); this._rethrowWithContext(e);
throw e; throw e;
} }
} }
@ -416,7 +416,7 @@ export class DebugAppView<T> extends AppView<T> {
try { try {
super.detectChanges(throwOnChange); super.detectChanges(throwOnChange);
} catch (e) { } catch (e) {
this._rethrowWithContext(e, e.stack); this._rethrowWithContext(e);
throw e; throw e;
} }
} }
@ -427,13 +427,13 @@ export class DebugAppView<T> extends AppView<T> {
return this._currentDebugContext = new DebugContext(this, nodeIndex, rowNum, colNum); return this._currentDebugContext = new DebugContext(this, nodeIndex, rowNum, colNum);
} }
private _rethrowWithContext(e: any, stack: any) { private _rethrowWithContext(e: any) {
if (!(e instanceof ViewWrappedException)) { if (!(e instanceof ViewWrappedError)) {
if (!(e instanceof ExpressionChangedAfterItHasBeenCheckedException)) { if (!(e instanceof ExpressionChangedAfterItHasBeenCheckedError)) {
this.cdMode = ChangeDetectorStatus.Errored; this.cdMode = ChangeDetectorStatus.Errored;
} }
if (isPresent(this._currentDebugContext)) { if (isPresent(this._currentDebugContext)) {
throw new ViewWrappedException(e, stack, this._currentDebugContext); throw new ViewWrappedError(e, this._currentDebugContext);
} }
} }
} }
@ -445,7 +445,7 @@ export class DebugAppView<T> extends AppView<T> {
try { try {
return superHandler(event); return superHandler(event);
} catch (e) { } catch (e) {
this._rethrowWithContext(e, e.stack); this._rethrowWithContext(e);
throw e; throw e;
} }
}; };

View File

@ -8,7 +8,7 @@
import {Injector} from '../di/injector'; import {Injector} from '../di/injector';
import {ListWrapper} from '../facade/collection'; import {ListWrapper} from '../facade/collection';
import {unimplemented} from '../facade/exceptions'; import {unimplemented} from '../facade/errors';
import {isPresent} from '../facade/lang'; import {isPresent} from '../facade/lang';
import {WtfScopeFn, wtfCreateScope, wtfLeave} from '../profile/profile'; import {WtfScopeFn, wtfCreateScope, wtfLeave} from '../profile/profile';
import {ComponentFactory, ComponentRef} from './component_factory'; import {ComponentFactory, ComponentRef} from './component_factory';

View File

@ -8,7 +8,7 @@
import {ChangeDetectorRef} from '../change_detection/change_detector_ref'; import {ChangeDetectorRef} from '../change_detection/change_detector_ref';
import {ChangeDetectorStatus} from '../change_detection/constants'; import {ChangeDetectorStatus} from '../change_detection/constants';
import {unimplemented} from '../facade/exceptions'; import {unimplemented} from '../facade/errors';
import {AppView} from './view'; import {AppView} from './view';
/** /**

View File

@ -11,13 +11,12 @@ import {devModeEqual} from '../change_detection/change_detection';
import {UNINITIALIZED} from '../change_detection/change_detection_util'; import {UNINITIALIZED} from '../change_detection/change_detection_util';
import {Inject, Injectable} from '../di/decorators'; import {Inject, Injectable} from '../di/decorators';
import {ListWrapper} from '../facade/collection'; import {ListWrapper} from '../facade/collection';
import {BaseException} from '../facade/exceptions';
import {isBlank, isPresent, looseIdentical} from '../facade/lang'; import {isBlank, isPresent, looseIdentical} from '../facade/lang';
import {ViewEncapsulation} from '../metadata/view'; import {ViewEncapsulation} from '../metadata/view';
import {RenderComponentType, Renderer, RootRenderer} from '../render/api'; import {RenderComponentType, Renderer, RootRenderer} from '../render/api';
import {Sanitizer} from '../security'; import {Sanitizer} from '../security';
import {AppElement} from './element'; import {AppElement} from './element';
import {ExpressionChangedAfterItHasBeenCheckedException} from './exceptions'; import {ExpressionChangedAfterItHasBeenCheckedError} from './errors';
@Injectable() @Injectable()
export class ViewUtils { export class ViewUtils {
@ -124,7 +123,7 @@ export function interpolate(
c3 + _toStringWithNull(a4) + c4 + _toStringWithNull(a5) + c5 + _toStringWithNull(a6) + c3 + _toStringWithNull(a4) + c4 + _toStringWithNull(a5) + c5 + _toStringWithNull(a6) +
c6 + _toStringWithNull(a7) + c7 + _toStringWithNull(a8) + c8 + _toStringWithNull(a9) + c9; c6 + _toStringWithNull(a7) + c7 + _toStringWithNull(a8) + c8 + _toStringWithNull(a9) + c9;
default: 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 { export function checkBinding(throwOnChange: boolean, oldValue: any, newValue: any): boolean {
if (throwOnChange) { if (throwOnChange) {
if (!devModeEqual(oldValue, newValue)) { if (!devModeEqual(oldValue, newValue)) {
throw new ExpressionChangedAfterItHasBeenCheckedException(oldValue, newValue, null); throw new ExpressionChangedAfterItHasBeenCheckedError(oldValue, newValue);
} }
return false; return false;
} else { } else {

View File

@ -7,7 +7,6 @@
*/ */
import {Map, MapWrapper, Set, SetWrapper, StringMapWrapper} from '../facade/collection'; import {Map, MapWrapper, Set, SetWrapper, StringMapWrapper} from '../facade/collection';
import {BaseException} from '../facade/exceptions';
import {isPresent} from '../facade/lang'; import {isPresent} from '../facade/lang';
import {Type} from '../type'; import {Type} from '../type';
import {PlatformReflectionCapabilities} from './platform_reflection_capabilities'; import {PlatformReflectionCapabilities} from './platform_reflection_capabilities';
@ -67,7 +66,7 @@ export class Reflector extends ReflectorReader {
*/ */
listUnusedKeys(): any[] { listUnusedKeys(): any[] {
if (this._usedKeys == null) { if (this._usedKeys == null) {
throw new BaseException('Usage tracking is disabled'); throw new Error('Usage tracking is disabled');
} }
var allTypes = MapWrapper.keys(this._injectableInfo); var allTypes = MapWrapper.keys(this._injectableInfo);
return allTypes.filter(key => !SetWrapper.has(this._usedKeys, key)); return allTypes.filter(key => !SetWrapper.has(this._usedKeys, key));

View File

@ -10,7 +10,7 @@ import {AnimationKeyframe} from '../../src/animation/animation_keyframe';
import {AnimationPlayer} from '../../src/animation/animation_player'; import {AnimationPlayer} from '../../src/animation/animation_player';
import {AnimationStyles} from '../../src/animation/animation_styles'; import {AnimationStyles} from '../../src/animation/animation_styles';
import {Injector} from '../di/injector'; import {Injector} from '../di/injector';
import {unimplemented} from '../facade/exceptions'; import {unimplemented} from '../facade/errors';
import {ViewEncapsulation} from '../metadata/view'; import {ViewEncapsulation} from '../metadata/view';
/** /**

View File

@ -8,7 +8,6 @@
import {Injectable} from '../di/decorators'; import {Injectable} from '../di/decorators';
import {Map, MapWrapper} from '../facade/collection'; import {Map, MapWrapper} from '../facade/collection';
import {BaseException} from '../facade/exceptions';
import {scheduleMicroTask} from '../facade/lang'; import {scheduleMicroTask} from '../facade/lang';
import {NgZone} from '../zone/ng_zone'; import {NgZone} from '../zone/ng_zone';
@ -68,7 +67,7 @@ export class Testability {
decreasePendingRequestCount(): number { decreasePendingRequestCount(): number {
this._pendingCount -= 1; this._pendingCount -= 1;
if (this._pendingCount < 0) { if (this._pendingCount < 0) {
throw new BaseException('pending async requests below zero'); throw new Error('pending async requests below zero');
} }
this._runCallbacksIfReady(); this._runCallbacksIfReady();
return this._pendingCount; return this._pendingCount;

View File

@ -7,7 +7,6 @@
*/ */
import {EventEmitter} from '../facade/async'; import {EventEmitter} from '../facade/async';
import {BaseException} from '../facade/exceptions';
import {NgZoneImpl} from './ng_zone_impl'; import {NgZoneImpl} from './ng_zone_impl';
@ -88,12 +87,12 @@ export class NgZone {
static isInAngularZone(): boolean { return NgZoneImpl.isInAngularZone(); } static isInAngularZone(): boolean { return NgZoneImpl.isInAngularZone(); }
static assertInAngularZone(): void { static assertInAngularZone(): void {
if (!NgZoneImpl.isInAngularZone()) { 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 { static assertNotInAngularZone(): void {
if (NgZoneImpl.isInAngularZone()) { 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!');
} }
} }

View File

@ -8,15 +8,13 @@
import {APP_BOOTSTRAP_LISTENER, APP_INITIALIZER, ChangeDetectorRef, CompilerFactory, Component, Injector, NgModule, PlatformRef, Type} from '@angular/core'; 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 {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 {ComponentRef} from '@angular/core/src/linker/component_factory';
import {BrowserModule} from '@angular/platform-browser'; import {BrowserModule} from '@angular/platform-browser';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter'; import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {DOCUMENT} from '@angular/platform-browser/src/dom/dom_tokens'; import {DOCUMENT} from '@angular/platform-browser/src/dom/dom_tokens';
import {expect} from '@angular/platform-browser/testing/matchers'; 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 {TestBed, async, inject, withModule} from '../testing';
import {SpyChangeDetectorRef} from './spies'; import {SpyChangeDetectorRef} from './spies';
@ -27,14 +25,14 @@ class SomeComponent {
export function main() { export function main() {
describe('bootstrap', () => { describe('bootstrap', () => {
var errorLogger: _ArrayLogger; var mockConsole: MockConsole;
var fakeDoc: Document; var fakeDoc: Document;
beforeEach(() => { beforeEach(() => {
fakeDoc = getDOM().createHtmlDocument(); fakeDoc = getDOM().createHtmlDocument();
const el = getDOM().createElement('comp', fakeDoc); const el = getDOM().createElement('comp', fakeDoc);
getDOM().appendChild(fakeDoc.body, el); getDOM().appendChild(fakeDoc.body, el);
errorLogger = new _ArrayLogger(); mockConsole = new MockConsole();
}); });
type CreateModuleOptions = {providers?: any[], ngDoBootstrap?: any, bootstrap?: any[]}; type CreateModuleOptions = {providers?: any[], ngDoBootstrap?: any, bootstrap?: any[]};
@ -48,12 +46,13 @@ export function main() {
} else { } else {
options = providersOrOptions || {}; options = providersOrOptions || {};
} }
const errorHandler = new ErrorHandler(false);
errorHandler._console = mockConsole as any;
@NgModule({ @NgModule({
providers: [ providers: [
{provide: Console, useValue: new _MockConsole()}, {provide: ErrorHandler, useValue: errorHandler}, {provide: DOCUMENT, useValue: fakeDoc},
{provide: ExceptionHandler, useValue: new ExceptionHandler(errorLogger, false)}, options.providers || []
{provide: DOCUMENT, useValue: fakeDoc}, options.providers || []
], ],
imports: [BrowserModule], imports: [BrowserModule],
declarations: [SomeComponent], declarations: [SomeComponent],
@ -153,7 +152,7 @@ export function main() {
// we don't have an injector and therefore no way of // we don't have an injector and therefore no way of
// getting the exception handler. So // getting the exception handler. So
// the error is only rethrown but not logged via the exception handler. // 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) => { .then(() => expect(false).toBe(true), (e) => {
expect(e).toBe('Test'); 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 = const expectedErrMsg =
`The module MyModule was bootstrapped, but it does not declare "@NgModule.bootstrap" components nor a "ngDoBootstrap" method. Please define one of these.`; `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(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 // we don't have an injector and therefore no way of
// getting the exception handler. So // getting the exception handler. So
// the error is only rethrown but not logged via the exception handler. // 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', it('should rethrow promise errors even if the exceptionHandler is not rethrowing',
@ -255,7 +254,7 @@ export function main() {
defaultPlatform.bootstrapModuleFactory(moduleFactory) defaultPlatform.bootstrapModuleFactory(moduleFactory)
.then(() => expect(false).toBe(true), (e) => { .then(() => expect(false).toBe(true), (e) => {
expect(e).toBe('Test'); 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 MyComp6 {
} }
class _ArrayLogger { class MockConsole {
res: any[] = []; res: any[] = [];
log(s: any): void { this.res.push(s); } log(s: any): void { this.res.push(s); }
logError(s: any): void { this.res.push(s); } error(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) {}
} }

View File

@ -12,7 +12,6 @@ import {ReflectiveInjectorDynamicStrategy, ReflectiveInjectorInlineStrategy, Ref
import {ResolvedReflectiveProvider_} from '@angular/core/src/di/reflective_provider'; import {ResolvedReflectiveProvider_} from '@angular/core/src/di/reflective_provider';
import {expect} from '@angular/platform-browser/testing/matchers'; import {expect} from '@angular/platform-browser/testing/matchers';
import {BaseException} from '../../src/facade/exceptions';
import {isBlank, isPresent, stringify} from '../../src/facade/lang'; import {isBlank, isPresent, stringify} from '../../src/facade/lang';
class CustomDependencyMetadata extends DependencyMetadata {} class CustomDependencyMetadata extends DependencyMetadata {}
@ -20,7 +19,7 @@ class CustomDependencyMetadata extends DependencyMetadata {}
class Engine {} class Engine {}
class BrokenEngine { class BrokenEngine {
constructor() { throw new BaseException('Broken Engine'); } constructor() { throw new Error('Broken Engine'); }
} }
class DashboardSoftware {} class DashboardSoftware {}
@ -332,7 +331,7 @@ export function main() {
} catch (e) { } catch (e) {
expect(e.message).toContain( expect(e.message).toContain(
`Error during instantiation of Engine! (${stringify(Car)} -> Engine)`); `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); expect(e.causeKey.token).toEqual(Engine);
} }
}); });
@ -364,7 +363,8 @@ export function main() {
{provide: Engine, useFactory: (() => isBroken ? new BrokenEngine() : new Engine())} {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; isBroken = false;

View File

@ -6,8 +6,16 @@
* found in the LICENSE file at https://angular.io/license * 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 {WrappedError} from '@angular/core/src/facade/errors';
import {BaseException, WrappedException, ExceptionHandler} from '../src/exceptions'; 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 { class _CustomException {
context = 'some context'; context = 'some context';
@ -15,74 +23,78 @@ class _CustomException {
} }
export function main() { 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', () => { it('should output exception', () => {
var e = ExceptionHandler.exceptionToString(new BaseException('message!')); var e = errorToString(new Error('message!'));
expect(e).toContain('message!'); expect(e).toContain('message!');
}); });
it('should output stackTrace', () => { it('should output stackTrace', () => {
var e = ExceptionHandler.exceptionToString(new BaseException('message!'), 'stack!'); var error = new Error('message!');
expect(e).toContain('stack!'); var stack = getStack(error);
}); var e = errorToString(error);
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!');
}); });
describe('context', () => { 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', () => { it('should print nested context', () => {
var original = new WrappedException('message!', null, null, 'context!'); var cause = new Error('message!');
var e = ExceptionHandler.exceptionToString(new WrappedException('message', original)); var stack = getStack(cause);
expect(e).toContain('context!'); var context = {
}); source: 'context!',
toString() { return 'Context'; }
it('should not print context when the passed-in exception is not a BaseException', () => { } as any as DebugContext;
var e = ExceptionHandler.exceptionToString(new _CustomException()); var original = new ViewWrappedError(cause, context);
expect(e).not.toContain('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', () => { describe('original exception', () => {
it('should print original exception message if available (original is BaseException)', () => { it('should print original exception message if available (original is Error)', () => {
var realOriginal = new BaseException('inner'); var realOriginal = new Error('inner');
var original = new WrappedException('wrapped', realOriginal); var stack = getStack(realOriginal);
var e = var original = new WrappedError('wrapped', realOriginal);
ExceptionHandler.exceptionToString(new WrappedException('wrappedwrapped', original)); var e = errorToString(new WrappedError('wrappedwrapped', original));
expect(e).toContain('inner'); expect(e).toContain(stack);
}); });
it('should print original exception message if available (original is not BaseException)', it('should print original exception message if available (original is not Error)', () => {
() => { var realOriginal = new _CustomException();
var realOriginal = new _CustomException(); var original = new WrappedError('wrapped', realOriginal);
var original = new WrappedException('wrapped', realOriginal); var e = errorToString(new WrappedError('wrappedwrapped', original));
var e = expect(e).toContain('custom');
ExceptionHandler.exceptionToString(new WrappedException('wrappedwrapped', original)); });
expect(e).toContain('custom');
});
}); });
describe('original stack', () => { describe('original stack', () => {
it('should print original stack if available', () => { it('should print original stack if available', () => {
var realOriginal = new BaseException('inner'); var realOriginal = new Error('inner');
var original = new WrappedException('wrapped', realOriginal, 'originalStack'); var stack = getStack(realOriginal);
var e = ExceptionHandler.exceptionToString( var original = new WrappedError('wrapped', realOriginal);
new WrappedException('wrappedwrapped', original, 'wrappedStack')); var e = errorToString(new WrappedError('wrappedwrapped', original));
expect(e).toContain('originalStack'); expect(e).toContain(stack);
}); });
}); });
}); });

View File

@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license * 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 {discardPeriodicTasks, fakeAsync, flushMicrotasks, tick} from '@angular/core/testing';
import {Log, beforeEach, ddescribe, describe, iit, inject, it, xit} from '@angular/core/testing/testing_internal'; import {Log, beforeEach, ddescribe, describe, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {expect} from '@angular/platform-browser/testing/matchers'; 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', () => { it('should complain if the test throws an exception during async calls', () => {
expect(() => { expect(() => {
fakeAsync(() => { fakeAsync(() => {
resolvedPromise.then((_) => { throw new BaseException('async'); }); resolvedPromise.then((_) => { throw new Error('async'); });
flushMicrotasks(); flushMicrotasks();
})(); })();
}).toThrowError('Uncaught (in promise): async'); }).toThrowError('Uncaught (in promise): Error: async');
}); });
it('should complain if a test throws an exception', () => { it('should complain if a test throws an exception', () => {
expect(() => { expect(() => { fakeAsync(() => { throw new Error('sync'); })(); }).toThrowError('sync');
fakeAsync(() => { throw new BaseException('sync'); })();
}).toThrowError('sync');
}); });
}); });

View File

@ -18,7 +18,6 @@ import {DomRootRenderer} from '@angular/platform-browser/src/dom/dom_renderer';
import {EventEmitter} from '../../src/facade/async'; import {EventEmitter} from '../../src/facade/async';
import {StringMapWrapper} from '../../src/facade/collection'; import {StringMapWrapper} from '../../src/facade/collection';
import {BaseException} from '../../src/facade/exceptions';
import {NumberWrapper, isBlank} from '../../src/facade/lang'; import {NumberWrapper, isBlank} from '../../src/facade/lang';
export function main() { export function main() {
@ -724,7 +723,7 @@ export function main() {
try { try {
ctx.detectChanges(false); ctx.detectChanges(false);
} catch (e) { } 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([]); expect(directiveLog.filter(['ngOnInit'])).toEqual([]);
})); }));
@ -821,7 +820,7 @@ export function main() {
try { try {
ctx.detectChanges(false); ctx.detectChanges(false);
} catch (e) { } 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([]); expect(directiveLog.filter(['ngAfterContentInit'])).toEqual([]);
})); }));
@ -935,7 +934,7 @@ export function main() {
try { try {
ctx.detectChanges(false); ctx.detectChanges(false);
} catch (e) { } 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([]); expect(directiveLog.filter(['ngAfterViewInit'])).toEqual([]);
})); }));
@ -1342,7 +1341,7 @@ class TestDirective implements OnInit, DoCheck, OnChanges, AfterContentInit, Aft
ngOnInit() { ngOnInit() {
this.log.add(this.name, 'ngOnInit'); this.log.add(this.name, 'ngOnInit');
if (this.throwOn == '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); StringMapWrapper.forEach(changes, (c: SimpleChange, key: string) => r[key] = c.currentValue);
this.changes = r; this.changes = r;
if (this.throwOn == 'ngOnChanges') { if (this.throwOn == 'ngOnChanges') {
throw new BaseException('Boom!'); throw new Error('Boom!');
} }
} }
ngAfterContentInit() { ngAfterContentInit() {
this.log.add(this.name, 'ngAfterContentInit'); this.log.add(this.name, 'ngAfterContentInit');
if (this.throwOn == 'ngAfterContentInit') { if (this.throwOn == 'ngAfterContentInit') {
throw new BaseException('Boom!'); throw new Error('Boom!');
} }
} }
ngAfterContentChecked() { ngAfterContentChecked() {
this.log.add(this.name, 'ngAfterContentChecked'); this.log.add(this.name, 'ngAfterContentChecked');
if (this.throwOn == 'ngAfterContentChecked') { if (this.throwOn == 'ngAfterContentChecked') {
throw new BaseException('Boom!'); throw new Error('Boom!');
} }
} }
ngAfterViewInit() { ngAfterViewInit() {
this.log.add(this.name, 'ngAfterViewInit'); this.log.add(this.name, 'ngAfterViewInit');
if (this.throwOn == 'ngAfterViewInit') { if (this.throwOn == 'ngAfterViewInit') {
throw new BaseException('Boom!'); throw new Error('Boom!');
} }
} }
ngAfterViewChecked() { ngAfterViewChecked() {
this.log.add(this.name, 'ngAfterViewChecked'); this.log.add(this.name, 'ngAfterViewChecked');
if (this.throwOn == 'ngAfterViewChecked') { if (this.throwOn == 'ngAfterViewChecked') {
throw new BaseException('Boom!'); throw new Error('Boom!');
} }
} }
ngOnDestroy() { ngOnDestroy() {
this.log.add(this.name, 'ngOnDestroy'); this.log.add(this.name, 'ngOnDestroy');
if (this.throwOn == 'ngOnDestroy') { if (this.throwOn == 'ngOnDestroy') {
throw new BaseException('Boom!'); throw new Error('Boom!');
} }
} }
} }

View File

@ -6,8 +6,10 @@
* found in the LICENSE file at https://angular.io/license * 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 {TestBed} from '@angular/core/testing';
import {Console} from '../../src/console'; import {Console} from '../../src/console';

View File

@ -23,7 +23,6 @@ import {dispatchEvent, el} from '@angular/platform-browser/testing/browser_util'
import {expect} from '@angular/platform-browser/testing/matchers'; import {expect} from '@angular/platform-browser/testing/matchers';
import {EventEmitter} from '../../src/facade/async'; import {EventEmitter} from '../../src/facade/async';
import {BaseException} from '../../src/facade/exceptions';
import {isBlank, isPresent, stringify} from '../../src/facade/lang'; import {isBlank, isPresent, stringify} from '../../src/facade/lang';
const ANCHOR_ELEMENT = new OpaqueToken('AnchorElement'); const ANCHOR_ELEMENT = new OpaqueToken('AnchorElement');
@ -2091,7 +2090,7 @@ class OtherDuplicateDir {
@Directive({selector: 'directive-throwing-error'}) @Directive({selector: 'directive-throwing-error'})
class DirectiveThrowingAnError { class DirectiveThrowingAnError {
constructor() { throw new BaseException('BOOM'); } constructor() { throw new Error('BOOM'); }
} }
@Component({ @Component({

View File

@ -11,14 +11,13 @@ import {Console} from '@angular/core/src/console';
import {ComponentFixture, TestBed, inject} from '@angular/core/testing'; import {ComponentFixture, TestBed, inject} from '@angular/core/testing';
import {expect} from '@angular/platform-browser/testing/matchers'; import {expect} from '@angular/platform-browser/testing/matchers';
import {BaseException} from '../../src/facade/exceptions';
import {stringify} from '../../src/facade/lang'; import {stringify} from '../../src/facade/lang';
import {NgModuleInjector} from '../../src/linker/ng_module_factory'; import {NgModuleInjector} from '../../src/linker/ng_module_factory';
class Engine {} class Engine {}
class BrokenEngine { class BrokenEngine {
constructor() { throw new BaseException('Broken Engine'); } constructor() { throw new Error('Broken Engine'); }
} }
class DashboardSoftware {} class DashboardSoftware {}

View File

@ -6,12 +6,11 @@
* found in the LICENSE file at https://angular.io/license * 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 {NgZone} from '@angular/core/src/zone/ng_zone';
import {async, fakeAsync, flushMicrotasks} from '@angular/core/testing'; 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 {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 {browserDetection} from '@angular/platform-browser/testing/browser_util';
import {BaseError} from '../../src/facade/errors';
import {isPresent, scheduleMicroTask} from '../../src/facade/lang'; import {isPresent, scheduleMicroTask} from '../../src/facade/lang';
var needsLongerTimers = browserDetection.isSlow || browserDetection.isEdge; var needsLongerTimers = browserDetection.isSlow || browserDetection.isEdge;
@ -95,7 +94,7 @@ export function main() {
setTimeout(() => { setTimeout(() => {
setTimeout(() => { setTimeout(() => {
resolve(null); resolve(null);
throw new BaseException('ccc'); throw new BaseError('ccc');
}, 0); }, 0);
}, 0); }, 0);
}); });
@ -118,7 +117,7 @@ export function main() {
scheduleMicroTask(() => { scheduleMicroTask(() => {
scheduleMicroTask(() => { scheduleMicroTask(() => {
resolve(null); resolve(null);
throw new BaseException('ddd'); throw new BaseError('ddd');
}); });
}); });
}); });
@ -153,7 +152,7 @@ export function main() {
setTimeout(() => { setTimeout(() => {
setTimeout(() => { setTimeout(() => {
resolve(null); resolve(null);
throw new BaseException('ccc'); throw new BaseError('ccc');
}, 0); }, 0);
}, 0); }, 0);
}); });
@ -720,7 +719,7 @@ function commonTests() {
it('should call the on error callback when it is invoked via zone.runGuarded', it('should call the on error callback when it is invoked via zone.runGuarded',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
macroTask(() => { macroTask(() => {
var exception = new BaseException('sync'); var exception = new BaseError('sync');
_zone.runGuarded(() => { throw exception; }); _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', it('should not call the on error callback but rethrow when it is invoked via zone.run',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
macroTask(() => { macroTask(() => {
var exception = new BaseException('sync'); var exception = new BaseError('sync');
expect(() => _zone.run(() => { throw exception; })).toThrowError('sync'); expect(() => _zone.run(() => { throw exception; })).toThrowError('sync');
expect(_errors.length).toBe(0); expect(_errors.length).toBe(0);
@ -743,7 +742,7 @@ function commonTests() {
it('should call onError for errors from microtasks', it('should call onError for errors from microtasks',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var exception = new BaseException('async'); var exception = new BaseError('async');
macroTask(() => { _zone.run(() => { scheduleMicroTask(() => { throw exception; }); }); }); macroTask(() => { _zone.run(() => { scheduleMicroTask(() => { throw exception; }); }); });

View File

@ -7,7 +7,6 @@
*/ */
import {ChangeDetectorRef, ComponentRef, DebugElement, ElementRef, NgZone, getDebugNode} from '../index'; import {ChangeDetectorRef, ComponentRef, DebugElement, ElementRef, NgZone, getDebugNode} from '../index';
import {BaseException} from '../src/facade/exceptions';
import {scheduleMicroTask} from '../src/facade/lang'; import {scheduleMicroTask} from '../src/facade/lang';
import {tick} from './fake_async'; import {tick} from './fake_async';
@ -146,7 +145,7 @@ export class ComponentFixture<T> {
*/ */
autoDetectChanges(autoDetect: boolean = true) { autoDetectChanges(autoDetect: boolean = true) {
if (this.ngZone == null) { 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._autoDetect = autoDetect;
this.detectChanges(); this.detectChanges();

View File

@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {BaseException} from '../index';
const FakeAsyncTestZoneSpec = (Zone as any)['FakeAsyncTestZoneSpec']; const FakeAsyncTestZoneSpec = (Zone as any)['FakeAsyncTestZoneSpec'];
@ -53,13 +52,13 @@ export function fakeAsync(fn: Function): (...args: any[]) => any {
return function(...args: any[]) { return function(...args: any[]) {
const proxyZoneSpec = ProxyZoneSpec.assertPresent(); const proxyZoneSpec = ProxyZoneSpec.assertPresent();
if (_inFakeAsyncCall) { if (_inFakeAsyncCall) {
throw new BaseException('fakeAsync() calls can not be nested'); throw new Error('fakeAsync() calls can not be nested');
} }
_inFakeAsyncCall = true; _inFakeAsyncCall = true;
try { try {
if (!_fakeAsyncTestZoneSpec) { if (!_fakeAsyncTestZoneSpec) {
if (proxyZoneSpec.getDelegate() instanceof 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(); _fakeAsyncTestZoneSpec = new FakeAsyncTestZoneSpec();
@ -76,13 +75,13 @@ export function fakeAsync(fn: Function): (...args: any[]) => any {
} }
if (_fakeAsyncTestZoneSpec.pendingPeriodicTimers.length > 0) { if (_fakeAsyncTestZoneSpec.pendingPeriodicTimers.length > 0) {
throw new BaseException( throw new Error(
`${_fakeAsyncTestZoneSpec.pendingPeriodicTimers.length} ` + `${_fakeAsyncTestZoneSpec.pendingPeriodicTimers.length} ` +
`periodic timer(s) still in the queue.`); `periodic timer(s) still in the queue.`);
} }
if (_fakeAsyncTestZoneSpec.pendingTimers.length > 0) { if (_fakeAsyncTestZoneSpec.pendingTimers.length > 0) {
throw new BaseException( throw new Error(
`${_fakeAsyncTestZoneSpec.pendingTimers.length} timer(s) still in the queue.`); `${_fakeAsyncTestZoneSpec.pendingTimers.length} timer(s) still in the queue.`);
} }
return res; return res;

View File

@ -6,9 +6,8 @@
* found in the LICENSE file at https://angular.io/license * 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 {ListWrapper} from '../src/facade/collection';
import {BaseException} from '../src/facade/exceptions';
import {FunctionWrapper, stringify} from '../src/facade/lang'; import {FunctionWrapper, stringify} from '../src/facade/lang';
import {Type} from '../src/type'; import {Type} from '../src/type';
@ -173,7 +172,7 @@ export class TestBed implements Injector {
*/ */
initTestEnvironment(ngModule: Type<any>, platform: PlatformRef) { initTestEnvironment(ngModule: Type<any>, platform: PlatformRef) {
if (this.platform || this.ngModule) { 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.platform = platform;
this.ngModule = ngModule; this.ngModule = ngModule;
@ -256,7 +255,7 @@ export class TestBed implements Injector {
this._moduleWithComponentFactories = this._moduleWithComponentFactories =
this._compiler.compileModuleAndAllComponentsSync(moduleType); this._compiler.compileModuleAndAllComponentsSync(moduleType);
} catch (e) { } catch (e) {
if (e instanceof ComponentStillLoadingError) { if (e.compType) {
throw new Error( throw new Error(
`This test module uses the component ${stringify(e.compType)} which is using a "templateUrl", but they were never compiled. ` + `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.`); `Please call "TestBed.compileComponents" before your test.`);
@ -296,7 +295,7 @@ export class TestBed implements Injector {
private _assertNotInstantiated(methodName: string, methodDescription: string) { private _assertNotInstantiated(methodName: string, methodDescription: string) {
if (this._instantiated) { if (this._instantiated) {
throw new BaseException( throw new Error(
`Cannot ${methodDescription} when the test module has already been instantiated. ` + `Cannot ${methodDescription} when the test module has already been instantiated. ` +
`Make sure you are not using \`inject\` before \`${methodName}\`.`); `Make sure you are not using \`inject\` before \`${methodName}\`.`);
} }
@ -344,7 +343,7 @@ export class TestBed implements Injector {
const componentFactory = this._moduleWithComponentFactories.componentFactories.find( const componentFactory = this._moduleWithComponentFactories.componentFactories.find(
(compFactory) => compFactory.componentType === component); (compFactory) => compFactory.componentType === component);
if (!componentFactory) { if (!componentFactory) {
throw new BaseException( throw new Error(
`Cannot create the component ${stringify(component)} as it was not imported into the testing module!`); `Cannot create the component ${stringify(component)} as it was not imported into the testing module!`);
} }
const noNgZone = this.get(ComponentFixtureNoNgZone, false); const noNgZone = this.get(ComponentFixtureNoNgZone, false);

View File

@ -7,7 +7,7 @@
*/ */
import {Compiler, CompilerOptions, ComponentMetadataType, DirectiveMetadataType, Injector, NgModuleMetadataType, PipeMetadataType} from '../index'; 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 {Type} from '../src/type';
import {MetadataOverride} from './metadata_override'; import {MetadataOverride} from './metadata_override';

View File

@ -6,59 +6,52 @@
* found in the LICENSE file at https://angular.io/license * 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 = (<any>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 = (<any>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 { 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;
}
} }

View File

@ -6,6 +6,8 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {BaseError} from './errors';
export interface BrowserNodeGlobal { export interface BrowserNodeGlobal {
Object: typeof Object; Object: typeof Object;
Array: typeof Array; Array: typeof Array;
@ -240,14 +242,6 @@ export class StringJoiner {
toString(): string { return this.parts.join(''); } 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 { export class NumberWrapper {
static toFixed(n: number, fractionDigits: number): string { return n.toFixed(fractionDigits); } static toFixed(n: number, fractionDigits: number): string { return n.toFixed(fractionDigits); }
@ -257,7 +251,7 @@ export class NumberWrapper {
static parseIntAutoRadix(text: string): number { static parseIntAutoRadix(text: string): number {
var result: number = parseInt(text); var result: number = parseInt(text);
if (isNaN(result)) { if (isNaN(result)) {
throw new NumberParseError('Invalid integer literal when parsing ' + text); throw new Error('Invalid integer literal when parsing ' + text);
} }
return result; return result;
} }
@ -277,8 +271,7 @@ export class NumberWrapper {
return result; return result;
} }
} }
throw new NumberParseError( throw new Error('Invalid integer literal when parsing ' + text + ' in base ' + radix);
'Invalid integer literal when parsing ' + text + ' in base ' + radix);
} }
// TODO: NaN is a valid literal but is returned by parseFloat to indicate an error. // TODO: NaN is a valid literal but is returned by parseFloat to indicate an error.

View File

@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {BaseException} from '@angular/core';
import {Observable} from '../facade/async'; import {Observable} from '../facade/async';
import {isPresent} from '../facade/lang'; import {isPresent} from '../facade/lang';
import {AbstractControl} from '../model'; import {AbstractControl} from '../model';
@ -19,7 +18,7 @@ import {AbstractControl} from '../model';
* @stable * @stable
*/ */
export abstract class AbstractControlDirective { 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; } get value(): any { return isPresent(this.control) ? this.control.value : null; }

View File

@ -6,14 +6,13 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {BaseException} from '@angular/core';
import {AbstractControlDirective} from './abstract_control_directive'; import {AbstractControlDirective} from './abstract_control_directive';
import {ControlValueAccessor} from './control_value_accessor'; import {ControlValueAccessor} from './control_value_accessor';
import {AsyncValidatorFn, ValidatorFn} from './validators'; import {AsyncValidatorFn, ValidatorFn} from './validators';
function unimplemented(): any { function unimplemented(): any {
throw new BaseException('unimplemented'); throw new Error('unimplemented');
} }
/** /**

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license * 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 {EventEmitter} from '../facade/async';
import {FormControl} from '../model'; import {FormControl} from '../model';

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license * 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'; import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../validators';

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license * 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 {ListWrapper} from '../facade/collection';
import {isPresent} from '../facade/lang'; import {isPresent} from '../facade/lang';
@ -139,7 +139,7 @@ export class RadioControlValueAccessor implements ControlValueAccessor,
} }
private _throwNameError(): void { 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 If you define both a name and a formControlName attribute on your radio button, their values
must match. Ex: <input type="radio" formControlName="food" name="food"> must match. Ex: <input type="radio" formControlName="food" name="food">
`); `);

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license * 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 {EventEmitter} from '../../facade/async';
import {ListWrapper, StringMapWrapper} from '../../facade/collection'; import {ListWrapper, StringMapWrapper} from '../../facade/collection';

View File

@ -6,13 +6,12 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {BaseException} from '@angular/core';
import {FormErrorExamples as Examples} from './error_examples'; import {FormErrorExamples as Examples} from './error_examples';
export class ReactiveErrors { export class ReactiveErrors {
static controlParentException(): void { 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 `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). 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 { static ngModelGroupException(): void {
throw new BaseException( throw new Error(
`formControlName cannot be used with an ngModelGroup parent. It is only compatible with parents `formControlName cannot be used with an ngModelGroup parent. It is only compatible with parents
that also have a "form" prefix: formGroupName, formArrayName, or formGroup. that also have a "form" prefix: formGroupName, formArrayName, or formGroup.
@ -35,7 +34,7 @@ export class ReactiveErrors {
${Examples.ngModelGroup}`); ${Examples.ngModelGroup}`);
} }
static missingFormException(): void { 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: Example:
@ -43,7 +42,7 @@ export class ReactiveErrors {
} }
static groupParentException(): void { 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 `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). 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 { 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 `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). directive and pass it an existing FormGroup instance (you can create one in your class).

Some files were not shown because too many files have changed in this diff Show More