import { AssertionError } from "./assertion_error.ts";import { stripAnsiCode } from "../fmt/colors.ts";
export function assertIsError<E extends Error = Error>( error: unknown, ErrorClass?: new (...args: any[]) => E, msgMatches?: string | RegExp, msg?: string,): asserts error is E { const msgSuffix = msg ? `: ${msg}` : "."; if (!(error instanceof Error)) { throw new AssertionError( `Expected "error" to be an Error object${msgSuffix}}`, ); } if (ErrorClass && !(error instanceof ErrorClass)) { msg = `Expected error to be instance of "${ErrorClass.name}", but was "${ typeof error === "object" ? error?.constructor?.name : "[not an object]" }"${msgSuffix}`; throw new AssertionError(msg); } let msgCheck; if (typeof msgMatches === "string") { msgCheck = stripAnsiCode(error.message).includes( stripAnsiCode(msgMatches), ); } if (msgMatches instanceof RegExp) { msgCheck = msgMatches.test(stripAnsiCode(error.message)); }
if (msgMatches && !msgCheck) { msg = `Expected error message to include ${ msgMatches instanceof RegExp ? msgMatches.toString() : JSON.stringify(msgMatches) }, but got ${ error instanceof Error ? JSON.stringify(error.message) : '"[not an Error]"' }${msgSuffix}`; throw new AssertionError(msg); }}