errors.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import type { BackgroundTaskKind, BackgroundTaskStatus, TaskError } from './types.js';
  2. export class BackgroundTaskError extends Error {
  3. constructor(
  4. message: string,
  5. readonly code: string,
  6. readonly details?: Record<string, unknown>,
  7. ) {
  8. super(message);
  9. this.name = 'BackgroundTaskError';
  10. }
  11. }
  12. export class TaskNotFoundError extends BackgroundTaskError {
  13. constructor(taskId: string) {
  14. super(`Background task not found: ${taskId}`, 'TASK_NOT_FOUND', { taskId });
  15. this.name = 'TaskNotFoundError';
  16. }
  17. }
  18. export class TaskAlreadyExistsError extends BackgroundTaskError {
  19. constructor(taskId: string) {
  20. super(`Background task already exists: ${taskId}`, 'TASK_ALREADY_EXISTS', { taskId });
  21. this.name = 'TaskAlreadyExistsError';
  22. }
  23. }
  24. export class TaskRunnerNotFoundError extends BackgroundTaskError {
  25. constructor(kind: BackgroundTaskKind) {
  26. super(`No background task runner registered for kind: ${kind}`, 'TASK_RUNNER_NOT_FOUND', {
  27. kind,
  28. });
  29. this.name = 'TaskRunnerNotFoundError';
  30. }
  31. }
  32. export class TaskRunnerAlreadyRegisteredError extends BackgroundTaskError {
  33. constructor(kind: BackgroundTaskKind) {
  34. super(`Background task runner already registered for kind: ${kind}`, 'TASK_RUNNER_EXISTS', {
  35. kind,
  36. });
  37. this.name = 'TaskRunnerAlreadyRegisteredError';
  38. }
  39. }
  40. export class InvalidTaskStatusTransitionError extends BackgroundTaskError {
  41. constructor(taskId: string, from: BackgroundTaskStatus, to: BackgroundTaskStatus) {
  42. super(
  43. `Invalid background task status transition for ${taskId}: ${from} -> ${to}`,
  44. 'INVALID_TASK_STATUS_TRANSITION',
  45. { taskId, from, to },
  46. );
  47. this.name = 'InvalidTaskStatusTransitionError';
  48. }
  49. }
  50. export function normalizeTaskError(error: unknown, fallbackCode = 'TASK_ERROR'): TaskError {
  51. if (error instanceof BackgroundTaskError) {
  52. return {
  53. message: error.message,
  54. code: error.code,
  55. details: error.details,
  56. };
  57. }
  58. if (error instanceof Error) {
  59. return {
  60. message: error.message,
  61. code: fallbackCode,
  62. details: error.stack ? { stack: error.stack } : undefined,
  63. };
  64. }
  65. return {
  66. message: String(error),
  67. code: fallbackCode,
  68. };
  69. }