UNPKG

@rarible/utils

Version:
41 lines (40 loc) 1.16 kB
import * as tg from "generic-type-guard"; import { CustomError } from "../custom/index.js"; import { extractErrorMessage } from "../utils/index.js"; /** * Represents error with the specific code * useful in cases when you have keyed-table of errors */ export class CodeError extends CustomError { static parse(error, data) { const message = extractErrorMessage(error); const code = extractErrorCode(error); return new CodeError(code, message, { cause: error, data: data, }); } constructor(code, message, options) { super(message, options); this.code = code; this.code = code; } } // fraction of PI CodeError.UNKNOWN_CODE = 14159265359; const hasCode = tg.isLikeObject({ code: tg.isSet, }); export function extractErrorCode(error) { if (hasCode(error)) { if (tg.isNumber(error.code)) return error.code; if (tg.isString(error.code)) { const parsedCode = parseInt(error.code); if (!isNaN(parsedCode)) { return parsedCode; } } } return CodeError.UNKNOWN_CODE; }