Skip to content

Commit

Permalink
feat(errors): add CustomError interface, update docs, add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Mar 13, 2024
1 parent f1ab427 commit d2ea8b2
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 7 deletions.
23 changes: 22 additions & 1 deletion packages/errors/src/deferror.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,30 @@
export interface CustomError extends Error {
/**
* The original message given to the error ctor (prior to applying
* prefix/suffix). If none was given this will be an empty string.
*/
origMessage: string;
}

/**
* Defines a custom error type/class which implements the {@link CustomError}
* interface.
*
* @remarks
* All error types in this package are defined via this function.
*
* @param prefix
* @param suffix
*/
export const defError = <T = string>(
prefix: (msg?: T) => string,
suffix: (msg?: T) => string = (msg) => (msg !== undefined ? ": " + msg : "")
) =>
class extends Error {
class extends Error implements CustomError {
origMessage: string;

constructor(msg?: T) {
super(prefix(msg) + suffix(msg));
this.origMessage = msg !== undefined ? String(msg) : "";
}
};
8 changes: 4 additions & 4 deletions packages/errors/src/ensure.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { assert } from "./assert.js";

/**
* Higher-order function to define ensurance assertions. Takes a `pred`icate
* Higher-order function to define assurance assertions. Takes a `pred`icate
* function and an `expected` (type) name, returns a new function which accepts
* 2 args (an arbitrary value `x` and optional error `msg`). When called, checks
* `x` for non-null and if so applies given `pred`icate. If result is false (or
* `x` is nullish) and iff {@link assert} is enabled, throws a
* 2 args: an arbitrary value `x` and optional error `msg`. When called, checks
* `x` for non-nullishness and if so applies given `pred`icate. If result is
* false (or `x` is nullish) and iff {@link assert} is enabled, throws a
* {@link AssertionError} with given `msg` (or a constructed default msg).
* Otherwise function is a no-op.
*
Expand Down
18 changes: 16 additions & 2 deletions packages/errors/test/main.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,18 @@
import { expect, test } from "bun:test";
// import * as errors from "../src/index.js"
import { illegalArgs, type CustomError } from "../src/index.js";

test.todo("errors", () => {});
test("nested", () => {
const foo = () => {
try {
illegalArgs("inner");
} catch (e) {
illegalArgs(`outer(${(<CustomError>e).origMessage})`);
}
};
try {
foo();
} catch (e) {
expect((<CustomError>e).origMessage).toBe("outer(inner)");
expect((<Error>e).message).toBe("illegal argument(s): outer(inner)");
}
});

0 comments on commit d2ea8b2

Please sign in to comment.