Skip to content

Commit a7644d5

Browse files
authored
feat(shared, server, opentelemetry, cloudflare)!: pass the original error to TracingSpan.recordException (#2494)
Closes #2493 `TracingSpan.recordException` now receives the value exactly as it was thrown, instead of a normalized `TracingException`. Backends get the cause chain, custom properties, `instanceof ORPCError` and object identity (the same error is recorded on the `handler`, `middleware.*` and `call_procedure` spans, so a `WeakSet` can deduplicate it). ```ts recordException(level: TracingExceptionLevel, error: unknown): void ``` Each backend decides how to serialize the value. Both built-in backends now pass the `Error` straight to the underlying span (or `String(error)` when it is not an error), because the OpenTelemetry SDK and the Workers runtime already read `name`, `message`, `stack` and `code` themselves. If the backend throws while reading the error (for example a `code` without `toString`, or a symbol as `code`), the string form is recorded instead, so the original error still propagates. For Workers this was checked against workerd 1.20261117.1 with a streaming tail worker: an `Error` instance is recorded with its name, message, stack and code. ## Breaking changes - `recordException` takes the thrown value. A custom `TracingSpan`, or code that calls `recordException` with an already normalized object, has to be updated. - `toTracingException` and `TracingException` are no longer exported from `@orpc/shared`. - An error whose `code` is neither a string nor a number is no longer recorded without a code: OpenTelemetry records `code.toString()` as `exception.type` when the code is truthy, and Workers Traces record the stringified code (`null` becomes `"null"`). ## Also in this PR - Bumps `wrangler` to 4.164.0 in `packages/cloudflare` and `playgrounds/cloudflare`. ## Tests `pnpm check` passes, and the shared, server, client, opentelemetry and cloudflare tests pass with 100% coverage of the changed files. The `packages/bun` tests were not run locally.
1 parent 0517019 commit a7644d5

11 files changed

Lines changed: 259 additions & 116 deletions

File tree

‎packages/cloudflare/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,6 @@
6262
"@cloudflare/vitest-plugin": "^1.5.0",
6363
"@vitest/coverage-istanbul": "^4.1.11",
6464
"vitest": "^4.1.11",
65-
"wrangler": "^4.156.2"
65+
"wrangler": "^4.164.0"
6666
}
6767
}

‎packages/cloudflare/src/tracer.test.ts‎

Lines changed: 36 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -188,24 +188,52 @@ describe('cloudflareTracer', () => {
188188
it('records error level exceptions natively and marks the span as failed', () => {
189189
const fake = createFakeSpan()
190190
const span = new CloudflareSpan(fake as any)
191-
const exception = { name: 'TypeError', message: 'boom', stack: 'stack', code: 'CODE' }
191+
const error = new TypeError('boom')
192192

193-
span.recordException('error', exception)
193+
span.recordException('error', error)
194194

195-
expect(fake.recordException).toHaveBeenCalledWith(exception)
195+
expect(fake.recordException).toHaveBeenCalledExactlyOnceWith(error)
196196
expect(fake.setStatus).toHaveBeenCalledWith({ code: 'error', message: 'boom' })
197197
})
198198

199199
it('records info level exceptions natively without marking the span as failed', () => {
200200
const fake = createFakeSpan()
201201
const span = new CloudflareSpan(fake as any)
202-
const exception = { name: 'AbortError', message: 'aborted', stack: 'stack' }
202+
const error = Object.assign(new Error('aborted'), { name: 'AbortError' })
203203

204-
span.recordException('info', exception)
204+
span.recordException('info', error)
205205

206-
expect(fake.recordException).toHaveBeenCalledWith(exception)
206+
expect(fake.recordException).toHaveBeenCalledExactlyOnceWith(error)
207207
expect(fake.setStatus).not.toHaveBeenCalled()
208208
})
209+
210+
it.each([
211+
['thrown', 'thrown'],
212+
[123, '123'],
213+
])('records %j, which is not an error, as its string form', (thrown, message) => {
214+
const fake = createFakeSpan()
215+
const span = new CloudflareSpan(fake as any)
216+
217+
span.recordException('error', thrown)
218+
219+
expect(fake.recordException).toHaveBeenCalledExactlyOnceWith(message)
220+
expect(fake.setStatus).toHaveBeenCalledWith({ code: 'error', message })
221+
})
222+
223+
it('records the string form of an error Workers fail to read', () => {
224+
const fake = createFakeSpan()
225+
const span = new CloudflareSpan(fake as any)
226+
const error = Object.assign(new Error('boom'), { code: Symbol('code') })
227+
228+
fake.recordException.mockImplementationOnce(() => {
229+
throw new TypeError('Cannot convert a Symbol value to a string')
230+
})
231+
span.recordException('error', error)
232+
233+
expect(fake.recordException).toHaveBeenNthCalledWith(1, error)
234+
expect(fake.recordException).toHaveBeenNthCalledWith(2, 'Error: boom')
235+
expect(fake.setStatus).toHaveBeenCalledWith({ code: 'error', message: 'boom' })
236+
})
209237
})
210238

211239
describe('with the runtime tracing api', () => {
@@ -224,8 +252,8 @@ describe('cloudflareTracer', () => {
224252
span.setAttribute('path', ['a', 'b'])
225253
span.addEvent('event')
226254
span.updateName('renamed')
227-
span.recordException('info', { name: 'AbortError', message: 'aborted' })
228-
span.recordException('error', { name: 'TypeError', message: 'boom', code: 'CODE' })
255+
span.recordException('info', Object.assign(new Error('aborted'), { name: 'AbortError' }))
256+
span.recordException('error', Object.assign(new TypeError('boom'), { code: 'CODE' }))
229257

230258
expect((tracer.getActiveSpan() as CloudflareSpan).span).toBe((span as CloudflareSpan).span)
231259

‎packages/cloudflare/src/tracer.ts‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ import type {
22
Promisable,
33
Tracer,
44
TracingAttributeValue,
5-
TracingException,
65
TracingExceptionLevel,
76
TracingSpan,
87
} from '@orpc/shared'
@@ -28,11 +27,22 @@ class CloudflareSpan implements TracingSpan {
2827
// Workers Traces have no custom span events
2928
}
3029

31-
recordException(level: TracingExceptionLevel, exception: TracingException): void {
32-
this.span.recordException(exception)
30+
recordException(level: TracingExceptionLevel, error: unknown): void {
31+
// Workers read the name, message, stack and code of an error themselves
32+
const exception = error instanceof Error ? error : String(error)
33+
34+
try {
35+
this.span.recordException(exception)
36+
} catch {
37+
// An error can hold values Workers fail to read, e.g. a symbol as `code`
38+
this.span.recordException(String(error))
39+
}
3340

3441
if (level === 'error') {
35-
this.span.setStatus({ code: 'error', message: exception.message })
42+
this.span.setStatus({
43+
code: 'error',
44+
message: typeof exception === 'string' ? exception : exception.message,
45+
})
3646
}
3747
}
3848

‎packages/opentelemetry/src/tracer.test.ts‎

Lines changed: 38 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -135,16 +135,14 @@ describe('openTelemetryTracer', () => {
135135
const tracer = createTracer()
136136

137137
const failed = tracer.startSpan('failed')
138-
failed.recordException('error', {
139-
name: 'Error',
140-
message: 'boom',
141-
stack: 'stack',
142-
code: 'CODE',
143-
})
138+
failed.recordException(
139+
'error',
140+
Object.assign(new Error('boom'), { stack: 'stack', code: 'CODE' }),
141+
)
144142
failed.end()
145143

146144
const aborted = tracer.startSpan('aborted')
147-
aborted.recordException('info', { name: 'AbortError', message: 'aborted' })
145+
aborted.recordException('info', Object.assign(new Error('aborted'), { name: 'AbortError' }))
148146
aborted.end()
149147

150148
const failedSpan = finishedSpan('failed')
@@ -161,6 +159,39 @@ describe('openTelemetryTracer', () => {
161159
expect(abortedSpan.events[0]?.name).toBe('exception')
162160
})
163161

162+
it('records numeric codes and values that are not errors', () => {
163+
const tracer = createTracer()
164+
165+
const coded = tracer.startSpan('coded')
166+
coded.recordException('error', Object.assign(new Error('boom'), { code: 123 }))
167+
coded.end()
168+
169+
const thrown = tracer.startSpan('thrown')
170+
thrown.recordException('error', 123)
171+
thrown.end()
172+
173+
expect(finishedSpan('coded').events[0]?.attributes).toMatchObject({
174+
'exception.type': '123',
175+
'exception.message': 'boom',
176+
})
177+
178+
const thrownSpan = finishedSpan('thrown')
179+
expect(thrownSpan.status).toEqual({ code: SpanStatusCode.ERROR, message: '123' })
180+
expect(thrownSpan.events[0]?.attributes).toEqual({ 'exception.message': '123' })
181+
})
182+
183+
it('records the string form of an error OpenTelemetry fails to read', () => {
184+
const tracer = createTracer()
185+
186+
const span = tracer.startSpan('unreadable')
187+
span.recordException('error', Object.assign(new Error('boom'), { code: Object.create(null) }))
188+
span.end()
189+
190+
const unreadableSpan = finishedSpan('unreadable')
191+
expect(unreadableSpan.status).toEqual({ code: SpanStatusCode.ERROR, message: 'boom' })
192+
expect(unreadableSpan.events[0]?.attributes).toEqual({ 'exception.message': 'Error: boom' })
193+
})
194+
164195
it('injects the trace context of a span into headers', () => {
165196
const tracer = createTracer()
166197
const span = tracer.startSpan('span') as OpenTelemetrySpan

‎packages/opentelemetry/src/tracer.ts‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ import type {
1010
Promisable,
1111
Tracer,
1212
TracingAttributeValue,
13-
TracingException,
1413
TracingExceptionLevel,
1514
TracingSpan,
1615
} from '@orpc/shared'
@@ -43,11 +42,22 @@ export class OpenTelemetrySpan implements TracingSpan {
4342
this.span.addEvent(name)
4443
}
4544

46-
recordException(level: TracingExceptionLevel, exception: TracingException): void {
47-
this.span.recordException(exception)
45+
recordException(level: TracingExceptionLevel, error: unknown): void {
46+
// OpenTelemetry reads the name, message, stack and code of an error itself
47+
const exception = error instanceof Error ? error : String(error)
48+
49+
try {
50+
this.span.recordException(exception)
51+
} catch {
52+
// An error can hold values OpenTelemetry fails to read, e.g. a `code` without `toString`
53+
this.span.recordException(String(error))
54+
}
4855

4956
if (level === 'error') {
50-
this.span.setStatus({ code: SpanStatusCode.ERROR, message: exception.message })
57+
this.span.setStatus({
58+
code: SpanStatusCode.ERROR,
59+
message: typeof exception === 'string' ? exception : exception.message,
60+
})
5161
}
5262
}
5363

‎packages/server/src/adapters/standard/handler.test.ts‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -611,10 +611,7 @@ describe('standardHandler', () => {
611611

612612
await expect(handler.handle(makeRequest(), OPTIONS)).rejects.toBe(error)
613613

614-
expect(span.recordException).toHaveBeenCalledExactlyOnceWith(
615-
'error',
616-
expect.objectContaining({ message: 'interceptor failure' }),
617-
)
614+
expect(span.recordException).toHaveBeenCalledExactlyOnceWith('error', error)
618615
expect(span.end).toHaveBeenCalledTimes(1)
619616
},
620617
)

‎packages/server/src/adapters/standard/handler.ts‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ import {
1111
recordSpanError,
1212
runWithSpan,
1313
toArray,
14-
toTracingException,
1514
traceAsyncIterator,
1615
traceReadableStream,
1716
value,
@@ -297,7 +296,7 @@ class TracingHandlerPlugin implements StandardHandlerPlugin<any> {
297296
* inside the event stream, already logged by the client interceptor.
298297
*/
299298
if (!(error instanceof EventStreamErrorEvent)) {
300-
span.recordException('error', toTracingException(error))
299+
span.recordException('error', error)
301300
}
302301
},
303302
onFinish() {
@@ -327,7 +326,7 @@ class TracingHandlerPlugin implements StandardHandlerPlugin<any> {
327326
* Any error here is internal (interceptor/framework), not business logic.
328327
* Indicates unexpected handler failure.
329328
*/
330-
span.recordException('error', toTracingException(error))
329+
span.recordException('error', error)
331330
},
332331
onFinish() {
333332
span.end()
@@ -345,7 +344,7 @@ class TracingHandlerPlugin implements StandardHandlerPlugin<any> {
345344
* Any error here is internal (interceptor/framework), not business logic.
346345
* Always recorded as an error, even when it is an abort error.
347346
*/
348-
span.recordException('error', toTracingException(e))
347+
span.recordException('error', e)
349348
span.end()
350349
throw e
351350
}

‎packages/shared/src/tracing.test.ts‎

Lines changed: 3 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import {
77
setTracer,
88
startSpan,
99
toSpanAttributeValue,
10-
toTracingException,
1110
} from './tracing'
1211

1312
function createMockSpan() {
@@ -87,10 +86,7 @@ describe('tracing', () => {
8786
const error = new Error('test')
8887
recordSpanError(mockSpan, error)
8988

90-
expect(mockSpan.recordException).toHaveBeenCalledWith(
91-
'error',
92-
expect.objectContaining({ message: 'test', name: 'Error' }),
93-
)
89+
expect(mockSpan.recordException).toHaveBeenCalledWith('error', error)
9490
})
9591

9692
it('records AbortError at info level', () => {
@@ -99,10 +95,7 @@ describe('tracing', () => {
9995
error.name = 'AbortError'
10096
recordSpanError(mockSpan, error)
10197

102-
expect(mockSpan.recordException).toHaveBeenCalledWith(
103-
'info',
104-
expect.objectContaining({ message: 'aborted', name: 'AbortError' }),
105-
)
98+
expect(mockSpan.recordException).toHaveBeenCalledWith('info', error)
10699
})
107100
})
108101

@@ -124,34 +117,6 @@ describe('tracing', () => {
124117
})
125118
})
126119

127-
describe('toTracingException', () => {
128-
it('converts error to exception', () => {
129-
const error = new Error('test')
130-
error.stack = 'stack'
131-
const exception = toTracingException(error)
132-
expect(exception).toEqual({ message: 'test', name: 'Error', stack: 'stack' })
133-
})
134-
135-
it('includes numeric code', () => {
136-
const error = new Error('test') as any
137-
error.code = 123
138-
const exception = toTracingException(error)
139-
expect(exception.code).toBe(123)
140-
})
141-
142-
it('includes string code', () => {
143-
const error = new Error('test') as any
144-
error.code = 'CODE'
145-
const exception = toTracingException(error)
146-
expect(exception.code).toBe('CODE')
147-
})
148-
149-
it('converts non-error to exception', () => {
150-
expect(toTracingException('test')).toEqual({ message: 'test' })
151-
expect(toTracingException(123)).toEqual({ message: '123' })
152-
})
153-
})
154-
155120
describe('toSpanAttributeValue', () => {
156121
it('serializes values', () => {
157122
expect(toSpanAttributeValue(undefined)).toBe('undefined')
@@ -225,10 +190,7 @@ describe('tracing', () => {
225190
const fn = vi.fn().mockRejectedValue(error)
226191

227192
await expect(runWithSpan('test', fn)).rejects.toThrow('fail')
228-
expect(mockSpan.recordException).toHaveBeenCalledWith(
229-
'error',
230-
expect.objectContaining({ message: 'fail' }),
231-
)
193+
expect(mockSpan.recordException).toHaveBeenCalledWith('error', error)
232194
expect(mockSpan.end).toHaveBeenCalledTimes(1)
233195
})
234196

‎packages/shared/src/tracing.ts‎

Lines changed: 4 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,6 @@ const TRACER_SYMBOL = /* @__PURE__ */ Symbol.for('ORPC_TRACER')
55

66
export type TracingAttributeValue = string | number | boolean | string[] | number[] | boolean[]
77

8-
export interface TracingException {
9-
name?: string
10-
message: string
11-
stack?: string
12-
code?: string | number
13-
}
14-
158
export type TracingHeaders = Record<string, string | string[] | undefined>
169

1710
export type TracingExceptionLevel = 'error' | 'info'
@@ -27,9 +20,10 @@ export interface TracingSpan {
2720
*/
2821
addEvent(name: string): void
2922
/**
30-
* Records an exception on the span. The `error` level also marks the span as failed.
23+
* Records a thrown value on the span, the backend decides how to serialize it.
24+
* The `error` level also marks the span as failed.
3125
*/
32-
recordException(level: TracingExceptionLevel, exception: TracingException): void
26+
recordException(level: TracingExceptionLevel, error: unknown): void
3327
end(): void
3428
}
3529

@@ -105,7 +99,7 @@ export function recordSpanError(span: TracingSpan | undefined, error: unknown):
10599
}
106100

107101
// DO NOT treat aborted error as error if happen during business logic (assumed)
108-
span.recordException(isAbortError(error) ? 'info' : 'error', toTracingException(error))
102+
span.recordException(isAbortError(error) ? 'info' : 'error', error)
109103
}
110104

111105
export function setSpanAttributeIfDefined(
@@ -120,24 +114,6 @@ export function setSpanAttributeIfDefined(
120114
span.setAttribute(key, value)
121115
}
122116

123-
export function toTracingException(error: unknown): TracingException {
124-
if (error instanceof Error) {
125-
const exception: TracingException = {
126-
message: error.message,
127-
name: error.name,
128-
stack: error.stack,
129-
}
130-
131-
if ('code' in error && (typeof error.code === 'string' || typeof error.code === 'number')) {
132-
exception.code = error.code
133-
}
134-
135-
return exception
136-
}
137-
138-
return { message: String(error) }
139-
}
140-
141117
export function toSpanAttributeValue(data: unknown): string {
142118
if (data === undefined) {
143119
return 'undefined'

0 commit comments

Comments
 (0)