|
| 1 | +const UNKNOWN_CODE = 'UNKNOWN'; |
| 2 | +const UNKNOWN_MESSAGE = 'Unknown error'; |
| 3 | + |
| 4 | +interface ErrorLike { |
| 5 | + message?: string; |
| 6 | + code?: string; |
| 7 | + msg?: string; |
| 8 | +} |
| 9 | + |
| 10 | +export class OcError extends Error { |
| 11 | + public readonly code: string; |
| 12 | + |
| 13 | + public static fromError(error: Error) { |
| 14 | + const ocError = new OcError( |
| 15 | + (error as OcError).code || UNKNOWN_CODE, |
| 16 | + error.message |
| 17 | + ); |
| 18 | + ocError.stack = error.stack; |
| 19 | + |
| 20 | + return ocError; |
| 21 | + } |
| 22 | + |
| 23 | + constructor(code: string, message: string) { |
| 24 | + super(message); |
| 25 | + |
| 26 | + this.code = code; |
| 27 | + this.name = this.constructor.name; |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +function isOcError(err: unknown): err is OcError { |
| 32 | + return ( |
| 33 | + err instanceof OcError || (!!err && (err as OcError).name === OcError.name) |
| 34 | + ); |
| 35 | +} |
| 36 | + |
| 37 | +function isErrorLike(data: unknown): data is ErrorLike { |
| 38 | + return ( |
| 39 | + !!data && |
| 40 | + (!!(data as ErrorLike).message || |
| 41 | + !!(data as ErrorLike).msg || |
| 42 | + !!(data as ErrorLike).code) |
| 43 | + ); |
| 44 | +} |
| 45 | + |
| 46 | +export function parseError(error: unknown): OcError { |
| 47 | + if (isOcError(error)) return error; |
| 48 | + |
| 49 | + if (error instanceof Error) { |
| 50 | + return OcError.fromError(error); |
| 51 | + } |
| 52 | + |
| 53 | + let message = 'Unknown error'; |
| 54 | + let code = UNKNOWN_CODE; |
| 55 | + |
| 56 | + if (isErrorLike(error)) { |
| 57 | + message = error.message || error.msg || UNKNOWN_MESSAGE; |
| 58 | + code = error.code || UNKNOWN_CODE; |
| 59 | + } else if (typeof error === 'string') { |
| 60 | + message = error; |
| 61 | + } |
| 62 | + |
| 63 | + return new OcError(code, message); |
| 64 | +} |
0 commit comments