Skip to content

Commit

Permalink
feat: add chartkit-error
Browse files Browse the repository at this point in the history
  • Loading branch information
korvin89 committed Jul 21, 2022
1 parent 22b6525 commit 7dd6adc
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/libs/chartkit-error/__tests__/chartkit-error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import {CHARTKIT_ERROR_CODE, ChartKitError, isChartKitError} from '../chartkit-error';
import type {ChartKitErrorArgs} from '../chartkit-error';

describe('libs/chartkit-error', () => {
test.each<[unknown, boolean] /* [error, expected] */>([
[new ChartKitError(), true],
[new Error(), false],
[null, false],
[undefined, false],
])('isChartKitError (args: %j)', (error, expected) => {
const result = isChartKitError(error);
expect(result).toEqual(expected);
});

test.each<[ChartKitErrorArgs | undefined, ChartKitErrorArgs['code']] /* [error, expected] */>([
[undefined, CHARTKIT_ERROR_CODE.UNKNOWN],
[{code: CHARTKIT_ERROR_CODE.NO_DATA}, CHARTKIT_ERROR_CODE.NO_DATA],
])('check ChartKitError code (args: %j)', (args, expected) => {
let result: ChartKitErrorArgs['code'] = '';

try {
throw new ChartKitError(args);
} catch (error) {
if (isChartKitError(error)) {
result = error.code;
}
}

expect(result).toEqual(expected);
});
});
35 changes: 35 additions & 0 deletions src/libs/chartkit-error/chartkit-error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
export type ChartKitErrorArgs = {
code?: number | string;
originalError?: Error;
message?: string;
};

export const CHARTKIT_ERROR_CODE = {
UNKNOWN: 'ERR.CK.UNKNOWN_ERROR',
UNKNOWN_PLUGIN: 'ERR.CK.UNKNOWN_PLUGIN',
NO_DATA: 'ERR.CK.NO_DATA',
};

export class ChartKitError extends Error {
readonly code: number | string;
readonly isChartKitError = true;

constructor({
originalError,
message,
code = CHARTKIT_ERROR_CODE.UNKNOWN,
}: ChartKitErrorArgs = {}) {
super(message);

this.code = code;

if (originalError) {
this.name = originalError.name;
this.stack = originalError.stack;
}
}
}

export const isChartKitError = (error: unknown): error is ChartKitError => {
return error instanceof Error && 'isChartKitError' in error;
};
2 changes: 2 additions & 0 deletions src/libs/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
export {CHARTKIT_ERROR_CODE, ChartKitError, isChartKitError} from './chartkit-error/chartkit-error';
export type {ChartKitErrorArgs} from './chartkit-error/chartkit-error';
export {settings} from './settings/settings';

0 comments on commit 7dd6adc

Please sign in to comment.