diff --git a/src/libs/chartkit-error/__tests__/chartkit-error.ts b/src/libs/chartkit-error/__tests__/chartkit-error.ts new file mode 100644 index 00000000..a25a2aa9 --- /dev/null +++ b/src/libs/chartkit-error/__tests__/chartkit-error.ts @@ -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); + }); +}); diff --git a/src/libs/chartkit-error/chartkit-error.ts b/src/libs/chartkit-error/chartkit-error.ts new file mode 100644 index 00000000..30008a3c --- /dev/null +++ b/src/libs/chartkit-error/chartkit-error.ts @@ -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; +}; diff --git a/src/libs/index.ts b/src/libs/index.ts index a2d4a60e..5604338d 100644 --- a/src/libs/index.ts +++ b/src/libs/index.ts @@ -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';