peerError.ts 984 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import { EventEmitter } from "eventemitter3";
  2. import logger from "./logger";
  3. export interface EventsWithError<ErrorType extends string> {
  4. error: (error: PeerError<`${ErrorType}`>) => void;
  5. }
  6. export class EventEmitterWithError<
  7. ErrorType extends string,
  8. Events extends EventsWithError<ErrorType>,
  9. > extends EventEmitter<Events, never> {
  10. /**
  11. * Emits a typed error message.
  12. *
  13. * @internal
  14. */
  15. emitError(type: ErrorType, err: string | Error): void {
  16. logger.error("Error:", err);
  17. // @ts-ignore
  18. this.emit("error", new PeerError<`${ErrorType}`>(`${type}`, err));
  19. }
  20. }
  21. /**
  22. * A PeerError is emitted whenever an error occurs.
  23. * It always has a `.type`, which can be used to identify the error.
  24. */
  25. export class PeerError<T extends string> extends Error {
  26. /**
  27. * @internal
  28. */
  29. constructor(type: T, err: Error | string) {
  30. if (typeof err === "string") {
  31. super(err);
  32. } else {
  33. super();
  34. Object.assign(this, err);
  35. }
  36. this.type = type;
  37. }
  38. public type: T;
  39. }