From 538da1238e7139ca675ddf26e3c79b32078c9e24 Mon Sep 17 00:00:00 2001 From: psychedelicious <4822129+psychedelicious@users.noreply.github.com> Date: Fri, 8 Nov 2024 19:04:43 +1000 Subject: [PATCH] feat(assert): store original message in `AssertionError` `AssertionError` wraps the message provided during instantiation with some additional text: ```ts const error = new AssertionError("message"); console.log(error.message); // 'Wrong assertion encountered: "message"' ``` This helpfully communicates that the error resulted from a failed assertion. Sometimes we want to access the original message without the wrapper text. For example, we may wish to surface the error directly to a user. This change adds an `originalMessage` property to `AssertionError` to store the original message without any wrapper text. The existing behaviour is unchanged, but library consumers now have access to the original message. Closes #35 --- src/assert.ts | 4 ++++ test/assertIs.ts | 9 +++++++++ 2 files changed, 13 insertions(+) diff --git a/src/assert.ts b/src/assert.ts index a05c062..d020399 100644 --- a/src/assert.ts +++ b/src/assert.ts @@ -5,9 +5,13 @@ export type { Equals } from "./Equals"; /** @see */ export class AssertionError extends Error { + originalMessage?: string; + constructor(msg: string | undefined) { super(`Wrong assertion encountered` + (!msg ? "" : `: "${msg}"`)); + this.originalMessage = msg; + Object.setPrototypeOf(this, new.target.prototype); if (!this.stack) { diff --git a/test/assertIs.ts b/test/assertIs.ts index 3c8855c..6f6decf 100644 --- a/test/assertIs.ts +++ b/test/assertIs.ts @@ -122,3 +122,12 @@ scope: { console.log("PASS"); } } + +/** + * `AssertionError` should store the original message in the `originalMessage` property. + */ +{ + const error = new AssertionError("message"); + assert(error.originalMessage === "message"); + console.log("PASS"); +}