-
-
Notifications
You must be signed in to change notification settings - Fork 143
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(errors): add CustomError interface, update docs, add tests
- Loading branch information
1 parent
f1ab427
commit d2ea8b2
Showing
3 changed files
with
42 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) : ""; | ||
} | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)"); | ||
} | ||
}); |