Skip to content

Commit dc70d25

Browse files
committed
refactor(core): simplify symbol initialization in That function and README examples
1 parent 4018292 commit dc70d25

2 files changed

Lines changed: 9 additions & 14 deletions

File tree

README.md

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -63,13 +63,9 @@ export const AppError = That({
6363

6464
// Dynamic message (with Payload)
6565
NotFound: (id: number) => `Resource ${id} not found`,
66-
6766
DatabaseError: (query: string) => `Database Error: ${query}`,
68-
6967
ConnectionError: (url: string) => `Failed to connect: ${url}`
70-
}).enroll(/** your external errors */)
71-
.enroll(/** ... */)
72-
.bridge(/** ... */)
68+
})
7369
```
7470

7571
### 2. Throw and Catch
@@ -78,7 +74,7 @@ export const AppError = That({
7874
import {AppErrors} from "./errors";
7975

8076
// Throwing
81-
throw AppError.NotFound(404);
77+
throw AppError.NotFound(123);
8278
```
8379

8480
## 🛠️ Advanced: Adopting External Errors
@@ -104,7 +100,7 @@ const ExAppError = AppError.enroll(MyLegacyError, AppError.NotFound, (e) => [Num
104100

105101
// Now, MyFamily.from can recognize and transform MyLegacyError instances
106102
const err = ExAppError.from(new MyLegacyError("123"));
107-
// err is now typed as AppError.NotFound
103+
// err is now typed as AppError.NotFound & payloadOf(err) === [123] (number)
108104
```
109105

110106
### `bridge` (One-to-Many/Conditional Mapping)
@@ -120,8 +116,10 @@ const ExAppError = AppError.bridge(HTTPException, (e, cases) => {
120116
return cases.NotFound(0);
121117
case 401:
122118
return cases.Unauthorized();
123-
default:
119+
case 500:
124120
return cases.DatabaseError(e.message);
121+
default:
122+
return cases.ConnectionError(e.res?.url ?? 'invalid url');
125123
}
126124
});
127125
```
@@ -135,13 +133,10 @@ error is passed, the TypeScript compiler will flag it.
135133
try {
136134
// ...
137135
} catch (e: unknown) {
138-
if (e instanceof Error) {
136+
if (e instanceof MyLegacyError) {
139137
// If 'e' might be an unregistered error class, TS will alert you here
140138
const error = MyFamily.from(e);
141-
142-
if (error.is(AppError.NotFound)) {
143-
// ...
144-
}
139+
// error is typed as MyFamily.NotFound
145140
}
146141
}
147142
```

packages/core/src/define.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ import {
1818
export function That<const M extends ErrorMap>(
1919
map: M
2020
): ErrorFamily<M> {
21-
const scope = Symbol("ErrorFamilyScope");
21+
const scope = Symbol();
2222
const cases: Partial<ErrorFamilyCases<M>> = {};
2323

2424
for (const key in map) {

0 commit comments

Comments
 (0)