From 52749e614bb6e5fd54e50d969aece4b40beb3f2c Mon Sep 17 00:00:00 2001 From: Ritesh Ghosh Date: Sat, 5 Oct 2024 17:28:29 +0530 Subject: [PATCH] feat: add HiAnimeError that extends Error and implements AniwatchError --- src/hianime/error.ts | 63 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 src/hianime/error.ts diff --git a/src/hianime/error.ts b/src/hianime/error.ts new file mode 100644 index 0000000..74bc7a0 --- /dev/null +++ b/src/hianime/error.ts @@ -0,0 +1,63 @@ +import { AxiosError } from "axios"; +import type { AniwatchError } from "../config/error.js"; + +const ANSI_RED_COLOR = "\x1b[31m"; +const ANSI_RESET_COLOR = "\x1b[0m"; + +const DEFAULT_ERROR_STATUS = 500; +const DEFAULT_ERROR_MESSAGE = "Something went wrong"; + +export class HiAnimeError extends Error implements AniwatchError { + public scraper: string; + public status: number = DEFAULT_ERROR_STATUS; + + constructor(errMsg: string, scraperName: string, status?: number) { + super(`${scraperName}: ${errMsg}`); + + this.name = HiAnimeError.name; + this.scraper = scraperName; + + if (status) { + this.status = + status >= 400 && status < 600 ? status : DEFAULT_ERROR_STATUS; // default status + } + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, HiAnimeError); + } + + this.logError(); + } + + static wrapError(err: HiAnimeError | any, scraperName: string): HiAnimeError { + if (err instanceof HiAnimeError) { + return err; + } + + if (err instanceof AxiosError) { + const statusText = err?.response?.statusText || DEFAULT_ERROR_MESSAGE; + return new HiAnimeError( + "fetchError: " + statusText, + scraperName, + err.status || DEFAULT_ERROR_STATUS + ); + } + + return new HiAnimeError(err?.message || DEFAULT_ERROR_MESSAGE, scraperName); + } + + private logError() { + console.error( + ANSI_RED_COLOR + + JSON.stringify( + { + scraper: this.scraper, + message: this?.message || DEFAULT_ERROR_MESSAGE, + }, + null, + 2 + ) + + ANSI_RESET_COLOR + ); + } +}