MCPcopy Create free account
hub / github.com/denoland/std / assertIsError

Function assertIsError

expect/_assert_is_error.ts:18–54  ·  view source on GitHub ↗
(
  error: unknown,
  // deno-lint-ignore no-explicit-any
  ErrorClass?: abstract new (...args: any[]) => E,
  msgMatches?: string | RegExp,
  msg?: string,
)

Source from the content-addressed store, hash-verified

16 * @param msg The optional message to display if the assertion fails.
17 */
18export function assertIsError<E extends Error = Error>(
19 error: unknown,
20 // deno-lint-ignore no-explicit-any
21 ErrorClass?: abstract new (...args: any[]) => E,
22 msgMatches?: string | RegExp,
23 msg?: string,
24): asserts error is E {
25 const msgPrefix = msg ? `${msg}: ` : "";
26 if (!(error instanceof Error)) {
27 throw new AssertionError(
28 `${msgPrefix}Expected "error" to be an Error object.`,
29 );
30 }
31 if (ErrorClass && !(error instanceof ErrorClass)) {
32 msg =
33 `${msgPrefix}Expected error to be instance of "${ErrorClass.name}", but was "${error?.constructor?.name}".`;
34 throw new AssertionError(msg);
35 }
36 let msgCheck;
37 if (typeof msgMatches === "string") {
38 msgCheck = stripAnsiCode(error.message).includes(
39 stripAnsiCode(msgMatches),
40 );
41 }
42 if (msgMatches instanceof RegExp) {
43 msgCheck = msgMatches.test(stripAnsiCode(error.message));
44 }
45
46 if (msgMatches && !msgCheck) {
47 msg = `${msgPrefix}Expected error message to include ${
48 msgMatches instanceof RegExp
49 ? msgMatches.toString()
50 : JSON.stringify(msgMatches)
51 }, but got ${JSON.stringify(error?.message)}.`;
52 throw new AssertionError(msg);
53 }
54}

Callers 1

toThrowFunction · 0.90

Calls 4

stripAnsiCodeFunction · 0.90
includesMethod · 0.80
stringifyMethod · 0.80
toStringMethod · 0.45

Tested by

no test coverage detected