Skip to content

Refactor FirebaseError #1725

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 30, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 2 additions & 14 deletions packages/app-types/private.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@

import { FirebaseApp, FirebaseNamespace } from '@firebase/app-types';
import { Observer, Subscribe } from '@firebase/util';
import { FirebaseError } from '@firebase/util';
import { FirebaseError, ErrorFactory } from '@firebase/util';

export interface FirebaseServiceInternals {
/**
Expand Down Expand Up @@ -61,18 +61,6 @@ export interface FirebaseServiceNamespace<T extends FirebaseService> {
(app?: FirebaseApp): T;
}

export interface FirebaseErrorFactory<T> {
create(code: T, data?: { [prop: string]: any }): FirebaseError;
}

export interface FirebaseErrorFactoryClass {
new (
service: string,
serviceName: string,
errors: { [code: string]: string }
): FirebaseErrorFactory<any>;
}

export interface FirebaseAuthTokenData {
accessToken: string;
}
Expand Down Expand Up @@ -155,6 +143,6 @@ export interface _FirebaseNamespace extends FirebaseNamespace {
/**
* Use to construct all thrown FirebaseError's.
*/
ErrorFactory: FirebaseErrorFactoryClass;
ErrorFactory: typeof ErrorFactory;
};
}
6 changes: 3 additions & 3 deletions packages/app/src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
* limitations under the License.
*/

import { ErrorFactory } from '@firebase/util';
import { ErrorFactory, ErrorMap } from '@firebase/util';

export const enum AppError {
NO_APP = 'no-app',
Expand All @@ -26,7 +26,7 @@ export const enum AppError {
INVALID_APP_ARGUMENT = 'invalid-app-argument'
}

const errors: { readonly [code in AppError]: string } = {
const errors: ErrorMap<AppError> = {
[AppError.NO_APP]:
"No Firebase App '{$name}' has been created - " +
'call Firebase App.initializeApp()',
Expand All @@ -40,7 +40,7 @@ const errors: { readonly [code in AppError]: string } = {
'Firebase App instance.'
};

let appErrors = new ErrorFactory<AppError>('app', 'Firebase', errors);
const appErrors = new ErrorFactory('app', 'Firebase', errors);

export function error(code: AppError, args?: { [name: string]: any }) {
throw appErrors.create(code, args);
Expand Down
6 changes: 3 additions & 3 deletions packages/messaging/src/models/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
* limitations under the License.
*/

import { ErrorFactory } from '@firebase/util';
import { ErrorFactory, ErrorMap } from '@firebase/util';

export const enum ErrorCode {
AVAILABLE_IN_WINDOW = 'only-available-in-window',
Expand Down Expand Up @@ -59,7 +59,7 @@ export const enum ErrorCode {
PUBLIC_KEY_DECRYPTION_FAILED = 'public-vapid-key-decryption-failed'
}

export const ERROR_MAP: { [code in ErrorCode]: string } = {
export const ERROR_MAP: ErrorMap<ErrorCode> = {
[ErrorCode.AVAILABLE_IN_WINDOW]:
'This method is available in a Window context.',
[ErrorCode.AVAILABLE_IN_SW]:
Expand Down Expand Up @@ -156,7 +156,7 @@ export const ERROR_MAP: { [code in ErrorCode]: string } = {
'The public VAPID key did not equal ' + '65 bytes when decrypted.'
};

export const errorFactory: ErrorFactory<string> = new ErrorFactory(
export const errorFactory = new ErrorFactory(
'messaging',
'Messaging',
ERROR_MAP
Expand Down
3 changes: 1 addition & 2 deletions packages/util/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,8 @@ export {
} from './src/environment';
export {
ErrorFactory,
ErrorList,
ErrorMap,
FirebaseError,
patchCapture,
StringLike
} from './src/errors';
export { jsonEval, stringify } from './src/json';
Expand Down
156 changes: 68 additions & 88 deletions packages/util/src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,115 +54,95 @@
* }
* }
*/
export type ErrorList<T> = { [code: string]: string };

export type ErrorMap<ErrorCode extends string> = {
readonly [K in ErrorCode]: string
};

const ERROR_NAME = 'FirebaseError';

export interface StringLike {
toString: () => string;
toString(): string;
}

let captureStackTrace: (obj: Object, fn?: Function) => void = (Error as any)
.captureStackTrace;

// Export for faking in tests
export function patchCapture(captureFake?: any): any {
let result: any = captureStackTrace;
captureStackTrace = captureFake;
return result;
export interface ErrorData {
[key: string]: StringLike | undefined;
}

export interface FirebaseError {
// Unique code for error - format is service/error-code-string
code: string;
export interface FirebaseError extends Error, ErrorData {
// Unique code for error - format is service/error-code-string.
readonly code: string;

// Developer-friendly error message.
message: string;
readonly message: string;

// Always 'FirebaseError'
name: string;
// Always 'FirebaseError'.
readonly name: typeof ERROR_NAME;

// Where available - stack backtrace in a string
stack: string;
}

export class FirebaseError implements FirebaseError {
public stack: string;
public name: string;

constructor(public code: string, public message: string) {
let stack: string;
// We want the stack value, if implemented by Error
if (captureStackTrace) {
// Patches this.stack, omitted calls above ErrorFactory#create
captureStackTrace(this, ErrorFactory.prototype.create);
} else {
try {
// In case of IE11, stack will be set only after error is raised.
// https://docs.microsoft.com/en-us/scripting/javascript/reference/stack-property-error-javascript
throw Error.apply(this, arguments);
} catch (err) {
this.name = ERROR_NAME;
// Make non-enumerable getter for the property.
Object.defineProperty(this, 'stack', {
get: function() {
return err.stack;
}
});
}
}
}
// Where available - stack backtrace in a string.
readonly stack?: string;
}

// Back-door inheritance
FirebaseError.prototype = Object.create(Error.prototype) as FirebaseError;
FirebaseError.prototype.constructor = FirebaseError;
(FirebaseError.prototype as any).name = ERROR_NAME;

export class ErrorFactory<T extends string> {
// Matches {$name}, by default.
public pattern = /\{\$([^}]+)}/g;

constructor(
private service: string,
private serviceName: string,
private errors: ErrorList<T>
) {
// empty
}

create(code: T, data?: { [prop: string]: StringLike }): FirebaseError {
if (data === undefined) {
data = {};
}
// Based on code from:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types
export class FirebaseError extends Error {
readonly name = ERROR_NAME;

let template = this.errors[code as string];
constructor(readonly code: string, message: string) {
super(message);

let fullCode = this.service + '/' + code;
let message: string;
// Fix For ES5
// https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
Object.setPrototypeOf(this, FirebaseError.prototype);

if (template === undefined) {
message = 'Error';
} else {
message = template.replace(this.pattern, (match, key) => {
let value = data![key];
return value !== undefined ? value.toString() : '<' + key + '?>';
});
// Maintains proper stack trace for where our error was thrown.
// Only available on V8.
if (Error.captureStackTrace) {
Error.captureStackTrace(this, ErrorFactory.prototype.create);
}
}
}

// Service: Error message (service/code).
message = this.serviceName + ': ' + message + ' (' + fullCode + ').';
let err = new FirebaseError(fullCode, message);

// Populate the Error object with message parts for programmatic
// accesses (e.g., e.file).
for (let prop in data) {
if (!data.hasOwnProperty(prop) || prop.slice(-1) === '_') {
continue;
export class ErrorFactory<ErrorCode extends string> {
constructor(
private readonly service: string,
private readonly serviceName: string,
private readonly errors: ErrorMap<ErrorCode>
) {}

create(code: ErrorCode, data: ErrorData = {}): FirebaseError {
const fullCode = `${this.service}/${code}`;
const template = this.errors[code];

const message = template ? replaceTemplate(template, data) : 'Error';
// Service Name: Error message (service/code).
const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;

const error = new FirebaseError(fullCode, fullMessage);

// Keys with an underscore at the end of their name are not included in
// error.data for some reason.
// TODO: Replace with Object.entries when lib is updated to es2017.
for (const key of Object.keys(data)) {
if (key.slice(-1) !== '_') {
if (key in error) {
console.warn(
`Overwriting FirebaseError base field "${key}" can cause unexpected behavior.`
);
}
error[key] = data[key];
}
(err as any)[prop] = data[prop];
}

return err;
return error;
}
}

function replaceTemplate(template: string, data: ErrorData): string {
return template.replace(PATTERN, (_, key) => {
const value = data[key];
return value != null ? value.toString() : `<${key}?>`;
});
}

const PATTERN = /\{\$([^}]+)}/g;
Loading