-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add HiAnimeError that extends Error and implements AniwatchError
- Loading branch information
1 parent
9d62023
commit 52749e6
Showing
1 changed file
with
63 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
); | ||
} | ||
} |