errors.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import type { ErrorContext } from './types';
  2. /**
  3. * E2E 测试专用错误类
  4. *
  5. * @description
  6. * 提供结构化的错误上下文信息,帮助开发者快速定位问题。
  7. *
  8. * @example
  9. * ```ts
  10. * throw new E2ETestError({
  11. * operation: 'selectRadixOption',
  12. * target: '残疾类型',
  13. * expected: '视力残疾',
  14. * available: ['听力残疾', '言语残疾', '肢体残疾']
  15. * });
  16. * ```
  17. */
  18. export class E2ETestError extends Error {
  19. /**
  20. * 创建一个 E2E 测试错误实例
  21. *
  22. * @param context - 结构化的错误上下文
  23. * @param message - 自定义错误消息(可选,默认自动生成)
  24. */
  25. constructor(
  26. public readonly context: ErrorContext,
  27. message?: string
  28. ) {
  29. super(message || formatErrorMessage(context));
  30. this.name = 'E2ETestError';
  31. }
  32. }
  33. /**
  34. * 格式化错误消息为友好格式
  35. *
  36. * @description
  37. * 内部函数,用于将 ErrorContext 转换为易读的错误消息。
  38. *
  39. * @internal
  40. *
  41. * @param context - 错误上下文
  42. * @returns 格式化后的错误消息
  43. */
  44. function formatErrorMessage(context: ErrorContext): string {
  45. const parts: string[] = [
  46. `❌ ${context.operation} failed`,
  47. `Target: ${context.target}`
  48. ];
  49. if (context.expected) {
  50. parts.push(`Expected: ${context.expected}`);
  51. }
  52. if (context.actual) {
  53. parts.push(`Actual: ${context.actual}`);
  54. }
  55. if (context.available && context.available.length > 0) {
  56. parts.push(`Available: ${context.available.join(', ')}`);
  57. }
  58. if (context.suggestion) {
  59. parts.push(`\n💡 ${context.suggestion}`);
  60. }
  61. return parts.join('\n');
  62. }
  63. /**
  64. * 抛出 E2E 测试错误的辅助函数
  65. *
  66. * @description
  67. * 便捷函数,用于抛出带上下文的 E2E 测试错误。永远抛出错误,返回类型为 `never`。
  68. *
  69. * @example
  70. * ```ts
  71. * if (!optionFound) {
  72. * throwError({
  73. * operation: 'selectRadixOption',
  74. * target: label,
  75. * expected: value,
  76. * available: availableOptions,
  77. * suggestion: '检查选项值是否正确'
  78. * });
  79. * }
  80. * ```
  81. *
  82. * @param context - 错误上下文
  83. * @throws {E2ETestError} 永远抛出错误
  84. */
  85. export function throwError(context: ErrorContext): never {
  86. throw new E2ETestError(context);
  87. }