@dxos/errors 0.12.0-next-73daef452f1464b62efdbca75fb0067c1066f264 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dxos/errors",
3
- "version": "0.12.0-next-73daef452f1464b62efdbca75fb0067c1066f264",
3
+ "version": "0.14.0",
4
4
  "description": "Error definitions",
5
5
  "homepage": "https://dxos.org",
6
6
  "bugs": "https://github.com/dxos/dxos/issues",
package/src/base.ts CHANGED
@@ -31,18 +31,31 @@ export class BaseError<Name extends string = string> extends Error {
31
31
  return class ExtendedError extends BaseError<Name> {
32
32
  static override name: Name = name;
33
33
 
34
+ /**
35
+ * Name equality, not an `instanceof`, so an error rebuilt from the wire still matches.
36
+ * A subclass that renames itself therefore does NOT match its parent, so define
37
+ * siblings rather than a renaming subclass.
38
+ */
34
39
  static is(error: unknown): error is BaseError {
35
40
  return typeof error === 'object' && error !== null && 'name' in error && error.name === name;
36
41
  }
37
42
 
43
+ /**
44
+ * Returns a `catch`/`mapError` callback that wraps a thrown value in this class.
45
+ * @param options.ifTypeDiffers - Pass an error of this class through untouched.
46
+ */
38
47
  static wrap(
39
48
  options?: Omit<BaseErrorOptions, 'cause'> & { ifTypeDiffers?: boolean },
40
49
  ): (error: unknown) => ExtendedError {
41
50
  const wrapFn = (error: unknown) => {
42
- if (options?.ifTypeDiffers === true && this.is(error)) {
51
+ if (options?.ifTypeDiffers === true && (this.is(error) || error instanceof this)) {
43
52
  return error as ExtendedError;
44
53
  }
45
- const newError: ExtendedError = new this({ message, ...options, cause: error });
54
+ const newError: ExtendedError = new this({
55
+ context: options?.context,
56
+ message: options?.message ?? messageOf(error) ?? message,
57
+ cause: error,
58
+ });
46
59
  Error.captureStackTrace(newError, wrapFn); // Position stack-trace to start from the caller of `wrap`.
47
60
  return newError;
48
61
  };
@@ -50,7 +63,7 @@ export class BaseError<Name extends string = string> extends Error {
50
63
  }
51
64
 
52
65
  constructor(options?: BaseErrorOptions) {
53
- super(name, { message: options?.message ?? message, ...options });
66
+ super(name, { cause: options?.cause, context: options?.context, message: options?.message ?? message });
54
67
  }
55
68
  };
56
69
  }
@@ -83,3 +96,21 @@ export class BaseError<Name extends string = string> extends Error {
83
96
  return this.name;
84
97
  }
85
98
  }
99
+
100
+ /**
101
+ * The message carried by a thrown value.
102
+ *
103
+ * Duck-types `message` rather than testing `instanceof Error`, so a cross-realm error or a
104
+ * rejected error-shaped object reads the same as a local one, matching how `encodeError`
105
+ * in `@dxos/protocols` decides what to put on the wire.
106
+ */
107
+ export const messageOf = (error: unknown): string | undefined => {
108
+ if (typeof error === 'string') {
109
+ return error;
110
+ }
111
+ if (typeof error === 'object' && error !== null && 'message' in error) {
112
+ const { message } = error as { message?: unknown };
113
+ return typeof message === 'string' ? message : undefined;
114
+ }
115
+ return undefined;
116
+ };
@@ -0,0 +1,57 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ /**
6
+ * The only two `DOMException` names that mean "the user (or an abort signal) stopped this",
7
+ * rather than "the operation failed". WebAuthn raises `NotAllowedError` both when the prompt is
8
+ * dismissed and when it times out; an aborted `AbortSignal` raises `AbortError`.
9
+ */
10
+ const CANCELLATION_NAMES: ReadonlySet<string> = new Set(['NotAllowedError', 'AbortError']);
11
+
12
+ /** Bound so a malformed chain (or a self-referential `cause`) cannot spin. */
13
+ const MAX_CAUSE_DEPTH = 8;
14
+
15
+ /**
16
+ * Marker a domain error sets to declare itself a user cancellation, so a generic reporter can
17
+ * recognise it without depending on the package that defines it (e.g. `PasskeyError.Dismissed`,
18
+ * which is raised for a dismissal the platform reported without a `DOMException`).
19
+ */
20
+ export interface Cancellation {
21
+ readonly cancellation: true;
22
+ }
23
+
24
+ const isMarked = (value: object): boolean => 'cancellation' in value && value.cancellation === true;
25
+
26
+ /**
27
+ * Whether a thrown value is a cancellation rather than a genuine failure.
28
+ *
29
+ * Walks the `cause` chain because a domain error wraps the original `DOMException` — the
30
+ * interactive ceremony that raised it sits several frames below the handler that reports it.
31
+ * Only the two names above match, so every other `DOMException` stays an error.
32
+ */
33
+ export const isCancellation = (error: unknown): boolean => {
34
+ let current: unknown = error;
35
+ for (let depth = 0; depth < MAX_CAUSE_DEPTH && current !== null && current !== undefined; ++depth) {
36
+ if (typeof current === 'object' && isMarked(current)) {
37
+ return true;
38
+ }
39
+ if (
40
+ typeof DOMException !== 'undefined' &&
41
+ current instanceof DOMException &&
42
+ CANCELLATION_NAMES.has(current.name)
43
+ ) {
44
+ return true;
45
+ }
46
+ if (typeof current !== 'object' || !('cause' in current)) {
47
+ return false;
48
+ }
49
+ const { cause } = current;
50
+ if (cause === current) {
51
+ return false;
52
+ }
53
+ current = cause;
54
+ }
55
+
56
+ return false;
57
+ };
package/src/context.ts ADDED
@@ -0,0 +1,24 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ /**
6
+ * Reads an error's structured `context`, which {@link BaseError} declares and a plain `Error` may
7
+ * still carry: a failure raised outside DXOS travels the same log and telemetry paths.
8
+ */
9
+ const readContext = (error: Error): object =>
10
+ 'context' in error && typeof error.context === 'object' && error.context ? error.context : {};
11
+
12
+ /**
13
+ * Merges structured detail into an error's `context`, returning the same error.
14
+ *
15
+ * Both of the repo's error codecs carry this field, so a failure annotated here reaches the
16
+ * downloadable log (`computeContext` in `@dxos/log`) and the reset dialog's copy payload without
17
+ * either of them knowing which subsystem produced it.
18
+ */
19
+ export const withContext = <T>(error: T, context: Record<string, unknown>): T => {
20
+ if (error instanceof Error) {
21
+ Object.assign(error, { context: { ...readContext(error), ...context } });
22
+ }
23
+ return error;
24
+ };
@@ -4,8 +4,8 @@
4
4
 
5
5
  import { describe, test } from 'vitest';
6
6
 
7
- import { BaseError, type BaseErrorOptions } from './base';
8
- import { SystemError } from './errors';
7
+ import { BaseError, type BaseErrorOptions, messageOf } from './base.ts';
8
+ import { SystemError } from './errors.ts';
9
9
 
10
10
  describe('errors', () => {
11
11
  test('error code and message, cause', ({ expect }) => {
@@ -51,6 +51,52 @@ describe('errors', () => {
51
51
  const error = new SystemError({ message: 'Test message' });
52
52
  expect(SystemError.is(error)).toBe(true);
53
53
  });
54
+
55
+ describe('wrap', () => {
56
+ test('carries the wrapped message so the cause is not the only place it survives', ({ expect }) => {
57
+ const error = SystemError.wrap()(new Error('disk full'));
58
+ expect(error).toBeInstanceOf(SystemError);
59
+ expect(error.message).toBe('disk full');
60
+ expect((error.cause as Error).message).toBe('disk full');
61
+ });
62
+
63
+ test('an explicit message wins over the wrapped one', ({ expect }) => {
64
+ expect(SystemError.wrap({ message: 'Upload failed.' })(new Error('disk full')).message).toBe('Upload failed.');
65
+ });
66
+
67
+ test('falls back to the class default when the value carries no message', ({ expect }) => {
68
+ expect(SystemError.wrap()(42).message).toBe('System error');
69
+ expect(SystemError.wrap()({}).message).toBe('System error');
70
+ });
71
+
72
+ test('reads a string and a plain error-shaped object', ({ expect }) => {
73
+ expect(SystemError.wrap()('boom').message).toBe('boom');
74
+ expect(SystemError.wrap()({ name: 'QuotaExceeded', message: 'too many' }).message).toBe('too many');
75
+ });
76
+
77
+ test('ifTypeDiffers passes an error of this class through untouched', ({ expect }) => {
78
+ const original = new SystemError({ message: 'Test message' });
79
+ expect(SystemError.wrap({ ifTypeDiffers: true })(original)).toBe(original);
80
+ expect(SystemError.wrap({ ifTypeDiffers: true })(new Error('other')).message).toBe('other');
81
+ });
82
+
83
+ test('positions the stack at the caller rather than inside wrap', ({ expect }) => {
84
+ const raise = () => SystemError.wrap()(new Error('inner'));
85
+ expect(raise().stack!.split('\n')[1]).to.match(/^ {4}at raise \(/);
86
+ });
87
+ });
88
+ });
89
+
90
+ describe('messageOf', () => {
91
+ test('reads Error, string and error-shaped values, and nothing else', ({ expect }) => {
92
+ expect(messageOf(new Error('boom'))).toBe('boom');
93
+ expect(messageOf('boom')).toBe('boom');
94
+ expect(messageOf({ message: 'boom' })).toBe('boom');
95
+ expect(messageOf({ message: 7 })).toBeUndefined();
96
+ expect(messageOf({})).toBeUndefined();
97
+ expect(messageOf(null)).toBeUndefined();
98
+ expect(messageOf(42)).toBeUndefined();
99
+ });
54
100
  });
55
101
 
56
102
  const throwError = () => {
package/src/errors.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { BaseError } from './base';
5
+ import { BaseError } from './base.ts';
6
6
 
7
7
  export class ApiError extends BaseError.extend('ApiError', 'API error') {}
8
8
 
package/src/index.ts CHANGED
@@ -2,5 +2,7 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- export * from './base';
6
- export * from './errors';
5
+ export * from './base.ts';
6
+ export * from './cancellation.ts';
7
+ export * from './context.ts';
8
+ export * from './errors.ts';