Skip to content

Commit

Permalink
feat: add HiAnimeError that extends Error and implements AniwatchError
Browse files Browse the repository at this point in the history
  • Loading branch information
ghoshRitesh12 committed Oct 5, 2024
1 parent 9d62023 commit 52749e6
Showing 1 changed file with 63 additions and 0 deletions.
63 changes: 63 additions & 0 deletions src/hianime/error.ts
Original file line number Diff line number Diff line change
@@ -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
);
}
}

0 comments on commit 52749e6

Please sign in to comment.