Skip to content

Commit

Permalink
feat: add error event
Browse files Browse the repository at this point in the history
  • Loading branch information
crimx committed May 14, 2024
1 parent e8c0eba commit c5aa4a7
Show file tree
Hide file tree
Showing 8 changed files with 431 additions and 198 deletions.
26 changes: 26 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,32 @@ remitter.emit("event1", "hello"); // logs "event1 hello"
remitter.emit("event2", "world"); // logs "event2 world"
```

### Listen to unhandled subscriber errors

```ts
import { Remitter } from "remitter";

interface EventData {
event1: string;
event2: string;
}

const remitter = new Remitter<EventData>();

remitter.onError(error => {
console.log(error);
});

remitter.emit("event1", () => {
throw new Error("error");
});

remitter.emit("event2", async () => {
await new Promise(resolve => setTimeout(resolve, 100));
throw new Error("async-error");
});
```

### Remit

You may tap into other events easily with `remit`. It is lazy-executed when listener count of the event name grows from 0 to 1. It is disposed when listener count of the event name drops from 1 to 0.
Expand Down
7 changes: 7 additions & 0 deletions src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,10 @@
export const ANY_EVENT = /* @__PURE__ */ Symbol();

export type ANY_EVENT = typeof ANY_EVENT;

/**
* A symbol that can be used as an event name to listen to unhandled subscriber errors.
*/
export const ERROR_EVENT = /* @__PURE__ */ Symbol();

export type ERROR_EVENT = typeof ERROR_EVENT;
9 changes: 7 additions & 2 deletions src/interface.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { ANY_EVENT } from "./constants";
import type { ANY_EVENT, ERROR_EVENT } from "./constants";

export type Fn = (...args: any[]) => any;

Expand All @@ -13,6 +13,8 @@ export type AnyRemitterListener<TConfig> = (
data: AnyEventData<TConfig>
) => void;

export type ErrorRemitterListener = (error: unknown) => void;

export type RemitterConfig<TConfig> = TConfig & {
[name in ANY_EVENT]: AnyEventData<TConfig>;
};
Expand All @@ -28,7 +30,10 @@ export type RemitterDatalessEventName<TConfig> = {

export type RemitterEventNames<TConfig> = keyof TConfig;

export type AllRemitterEventNames<TConfig> = keyof TConfig | ANY_EVENT;
export type AllRemitterEventNames<TConfig> =
| keyof TConfig
| ANY_EVENT
| ERROR_EVENT;

export type RemitterListener<
TConfig,
Expand Down
65 changes: 0 additions & 65 deletions src/relay.ts

This file was deleted.

Loading

0 comments on commit c5aa4a7

Please sign in to comment.