( error: unknown, // deno-lint-ignore no-explicit-any ErrorClass?: abstract new (...args: any[]) => E, msgMatches?: string | RegExp, msg?: string, )
| 27 | * @param msg The optional message to display if the assertion fails. |
| 28 | */ |
| 29 | export function assertIsError<E extends Error = Error>( |
| 30 | error: unknown, |
| 31 | // deno-lint-ignore no-explicit-any |
| 32 | ErrorClass?: abstract new (...args: any[]) => E, |
| 33 | msgMatches?: string | RegExp, |
| 34 | msg?: string, |
| 35 | ): asserts error is E { |
| 36 | const msgSuffix = msg ? `: ${msg}` : "."; |
| 37 | if (!(error instanceof Error)) { |
| 38 | throw new AssertionError( |
| 39 | `Expected "error" to be an Error object${msgSuffix}`, |
| 40 | ); |
| 41 | } |
| 42 | if (ErrorClass && !(error instanceof ErrorClass)) { |
| 43 | msg = |
| 44 | `Expected error to be instance of "${ErrorClass.name}", but was "${error?.constructor?.name}"${msgSuffix}`; |
| 45 | throw new AssertionError(msg); |
| 46 | } |
| 47 | let msgCheck; |
| 48 | if (typeof msgMatches === "string") { |
| 49 | msgCheck = stripAnsiCode(error.message).includes( |
| 50 | stripAnsiCode(msgMatches), |
| 51 | ); |
| 52 | } |
| 53 | if (msgMatches instanceof RegExp) { |
| 54 | msgCheck = msgMatches.test(stripAnsiCode(error.message)); |
| 55 | } |
| 56 | |
| 57 | if (msgMatches && !msgCheck) { |
| 58 | msg = `Expected error message to include ${ |
| 59 | msgMatches instanceof RegExp |
| 60 | ? msgMatches.toString() |
| 61 | : JSON.stringify(msgMatches) |
| 62 | }, but got ${JSON.stringify(error?.message)}${msgSuffix}`; |
| 63 | throw new AssertionError(msg); |
| 64 | } |
| 65 | } |
no test coverage detected
searching dependent graphs…