hostUncaughtExceptionGuard.test.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { describe, expect, it, vi } from "vitest";
  2. import {
  3. createHostUncaughtExceptionHandler,
  4. isRecoverableHostAllocationError,
  5. } from "../src/host/hostUncaughtExceptionGuard.js";
  6. describe("host uncaught exception guard", () => {
  7. it("识别 TLS 证书投影期间的内存分配失败", () => {
  8. const error = new RangeError("Failed to allocate memory");
  9. error.stack = [
  10. "RangeError: Failed to allocate memory",
  11. " at TLSSocket.getPeerCertificate (node:_tls_wrap:1115:35)",
  12. ].join("\n");
  13. expect(isRecoverableHostAllocationError(error)).toBe(true);
  14. });
  15. it("仅恢复明确的内存分配 RangeError", () => {
  16. expect(isRecoverableHostAllocationError(new Error("Failed to allocate memory"))).toBe(false);
  17. expect(isRecoverableHostAllocationError(new RangeError("Invalid array length"))).toBe(false);
  18. });
  19. it("内存分配异常只上报恢复事件,不进入 fatal 退出链路", () => {
  20. const onRecovered = vi.fn();
  21. const onFatal = vi.fn();
  22. const handler = createHostUncaughtExceptionHandler({ onRecovered, onFatal });
  23. const error = new RangeError("Failed to allocate memory");
  24. handler(error, "uncaughtException");
  25. expect(onRecovered).toHaveBeenCalledWith(error, "uncaughtException");
  26. expect(onFatal).not.toHaveBeenCalled();
  27. });
  28. it("其他未捕获异常仍进入 fatal 退出链路", () => {
  29. const onRecovered = vi.fn();
  30. const onFatal = vi.fn();
  31. const handler = createHostUncaughtExceptionHandler({ onRecovered, onFatal });
  32. const error = new Error("unexpected");
  33. handler(error, "unhandledRejection");
  34. expect(onRecovered).not.toHaveBeenCalled();
  35. expect(onFatal).toHaveBeenCalledWith(error, "unhandledRejection");
  36. });
  37. it("恢复日志自身失败时不重新抛出进程级异常", () => {
  38. const handler = createHostUncaughtExceptionHandler({
  39. onRecovered: () => {
  40. throw new Error("logger unavailable");
  41. },
  42. onFatal: vi.fn(),
  43. });
  44. expect(() =>
  45. handler(new RangeError("Failed to allocate memory"), "uncaughtException"),
  46. ).not.toThrow();
  47. });
  48. });