failure.ts 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. export type TuiFailureCategory =
  2. | 'invocation'
  3. | 'config'
  4. | 'runtime'
  5. | 'protocol'
  6. | 'internal'
  7. | 'cancelled'
  8. | 'brokenPipe';
  9. export interface TuiFailureOptions extends ErrorOptions {
  10. code: string;
  11. retryable?: boolean;
  12. details?: Readonly<Record<string, unknown>>;
  13. }
  14. export class TuiFailure extends Error {
  15. readonly code: string;
  16. readonly retryable: boolean;
  17. readonly details?: Readonly<Record<string, unknown>>;
  18. constructor(
  19. readonly category: TuiFailureCategory,
  20. message: string,
  21. options: TuiFailureOptions,
  22. ) {
  23. super(message, options);
  24. this.name = 'TuiFailure';
  25. this.code = options.code;
  26. this.retryable = options.retryable ?? false;
  27. this.details = options.details;
  28. }
  29. }
  30. export function toTuiFailure(
  31. error: unknown,
  32. fallback: Pick<TuiFailureOptions, 'code' | 'retryable'> & {
  33. category: TuiFailureCategory;
  34. },
  35. ): TuiFailure {
  36. if (error instanceof TuiFailure) return error;
  37. return new TuiFailure(fallback.category, error instanceof Error ? error.message : String(error), {
  38. code: fallback.code,
  39. retryable: fallback.retryable,
  40. cause: error,
  41. });
  42. }