Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion packages/core/realtime-js/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
"test:ci": "vitest run --coverage"
},
"dependencies": {
"@supabase/phoenix": "^0.4.0",
"@supabase/phoenix": "^0.4.1",
"@types/ws": "^8.18.1",
"tslib": "2.8.1",
"ws": "^8.18.2"
Expand Down
9 changes: 4 additions & 5 deletions packages/core/realtime-js/src/RealtimeChannel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import type {
} from './RealtimePresence'
import * as Transformers from './lib/transformers'
import { httpEndpointURL } from './lib/transformers'
import { normalizeChannelError } from './lib/normalizeChannelError'
import ChannelAdapter from './phoenix/channelAdapter'
import { ChannelBindingCallback, ChannelOnErrorCallback } from './phoenix/types'
import type { Timer } from './phoenix/types'
Expand Down Expand Up @@ -304,7 +305,7 @@ export default class RealtimeChannel {
}

this._onError((reason: unknown) => {
callback?.(REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR, reason as Error)
callback?.(REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR, normalizeChannelError(reason))
})

this._onClose(() => callback?.(REALTIME_SUBSCRIBE_STATES.CLOSED))
Expand All @@ -329,10 +330,8 @@ export default class RealtimeChannel {
})
.receive('error', (error: { [key: string]: any }) => {
this.state = CHANNEL_STATES.errored
callback?.(
REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR,
new Error(JSON.stringify(Object.values(error).join(', ') || 'error'))
)
const message = Object.values(error).join(', ') || 'error'
callback?.(REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR, new Error(message, { cause: error }))
})
.receive('timeout', () => {
callback?.(REALTIME_SUBSCRIBE_STATES.TIMED_OUT)
Expand Down
30 changes: 30 additions & 0 deletions packages/core/realtime-js/src/lib/normalizeChannelError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/**
* Normalize the various shapes a channel error reason can take into a real `Error`.
*
* Transport-level channel errors arrive as a `CloseEvent`, a transport `Event`, an `Error`,
* a string, or `undefined` depending on which path in the underlying socket fired. Server-reply
* errors arrive as a payload object. This helper produces a consistent `Error` for every case
* and preserves the original via `cause` so callers can still inspect the raw event.
*/
export function normalizeChannelError(reason: unknown): Error {
if (reason instanceof Error) {
return reason
}

if (typeof reason === 'string') {
return new Error(reason)
}

if (reason && typeof reason === 'object') {
const obj = reason as Record<string, unknown>

if (typeof obj.code === 'number') {
const detail = typeof obj.reason === 'string' && obj.reason ? ` (${obj.reason})` : ''
return new Error(`socket closed: ${obj.code}${detail}`, { cause: reason })
}

return new Error('channel error: transport failure', { cause: reason })
}

return new Error('channel error: connection lost')
}
69 changes: 69 additions & 0 deletions packages/core/realtime-js/test/RealtimeChannel.errors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -573,3 +573,72 @@ describe('Trigger Function Error Handling', () => {
})
})
})

describe('CHANNEL_ERROR callback receives a real Error', () => {
beforeEach(async () => {
testSetup.connect()
await testSetup.socketConnected()
})

test('transport phx_error with a CloseEvent payload yields a real Error with cause', () => {
const callback = vi.fn()
channel = testSetup.client.channel('test-transport-close')
channel.subscribe(callback)

const closeEvent = { code: 1006, reason: 'Network Failure' }
channel.channelAdapter.getChannel().trigger('phx_error', closeEvent)

expect(callback).toHaveBeenCalledWith('CHANNEL_ERROR', expect.any(Error))
const errorCall = callback.mock.calls.find((call) => call[0] === 'CHANNEL_ERROR')!
const err = errorCall[1] as Error
expect(err.message).toBe('socket closed: 1006 (Network Failure)')
expect(err.cause).toBe(closeEvent)
})

test('transport phx_error with an Error payload (heartbeat timeout) is forwarded as-is', () => {
const callback = vi.fn()
channel = testSetup.client.channel('test-heartbeat-timeout')
channel.subscribe(callback)

const heartbeatErr = new Error('heartbeat timeout')
channel.channelAdapter.getChannel().trigger('phx_error', heartbeatErr)

const errorCall = callback.mock.calls.find((call) => call[0] === 'CHANNEL_ERROR')!
expect(errorCall[1]).toBe(heartbeatErr)
})

test('transport phx_error with no payload still produces a real Error (defensive)', () => {
const callback = vi.fn()
channel = testSetup.client.channel('test-undefined-reason')
channel.subscribe(callback)

channel.channelAdapter.getChannel().trigger('phx_error')

const errorCall = callback.mock.calls.find((call) => call[0] === 'CHANNEL_ERROR')!
const err = errorCall[1] as Error
expect(err).toBeInstanceOf(Error)
expect(err.message).toBe('channel error: connection lost')
})

test('server-reply error path produces an Error with the joined message and cause', () => {
const callback = vi.fn()
channel = testSetup.client.channel('test-server-error')
channel.subscribe(callback)

channel.joinPush.trigger('error', {
reason: 'Authentication failed',
details: 'Invalid API key',
})

const errorCall = callback.mock.calls.find((call) => call[0] === 'CHANNEL_ERROR')!
const err = errorCall[1] as Error
expect(err).toBeInstanceOf(Error)
expect(err.message).toContain('Authentication failed')
expect(err.message).toContain('Invalid API key')
expect(err.message).not.toMatch(/^"/)
expect(err.cause).toEqual({
reason: 'Authentication failed',
details: 'Invalid API key',
})
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,10 @@ describe('socket close event', () => {
testClient.mockServer.close({ code: 1000, reason: '', wasClean: true })
await testClient.socketClosed()

expect(spy).toHaveBeenCalledWith(CHANNEL_EVENTS.error)
expect(spy).toHaveBeenCalledWith(
CHANNEL_EVENTS.error,
expect.objectContaining({ type: 'close', code: 1000, wasClean: true })
)
})
})

Expand All @@ -129,6 +132,9 @@ describe('_onConnError', () => {
const spy = vi.spyOn(channel.channelAdapter.getChannel(), 'trigger')
testClient.mockServer.simulate('error')

expect(spy).toHaveBeenCalledWith(CHANNEL_EVENTS.error)
expect(spy).toHaveBeenCalledWith(
CHANNEL_EVENTS.error,
expect.objectContaining({ type: 'error' })
)
})
})
63 changes: 63 additions & 0 deletions packages/core/realtime-js/test/normalizeChannelError.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { describe, expect, test } from 'vitest'
import { normalizeChannelError } from '../src/lib/normalizeChannelError'

describe('normalizeChannelError', () => {
test('returns the original Error untouched', () => {
const original = new Error('boom')
expect(normalizeChannelError(original)).toBe(original)
})

test('preserves Error subclasses', () => {
class CustomError extends Error {}
const original = new CustomError('custom')
const normalized = normalizeChannelError(original)
expect(normalized).toBe(original)
expect(normalized).toBeInstanceOf(CustomError)
})

test('wraps a string into an Error with the same message', () => {
const result = normalizeChannelError('something failed')
expect(result).toBeInstanceOf(Error)
expect(result.message).toBe('something failed')
})

test('formats a CloseEvent-shaped object with code and reason', () => {
const closeEvent = { code: 1006, reason: 'abnormal closure' }
const result = normalizeChannelError(closeEvent)
expect(result).toBeInstanceOf(Error)
expect(result.message).toBe('socket closed: 1006 (abnormal closure)')
expect(result.cause).toBe(closeEvent)
})

test('formats a CloseEvent without reason', () => {
const closeEvent = { code: 1000 }
const result = normalizeChannelError(closeEvent)
expect(result.message).toBe('socket closed: 1000')
expect(result.cause).toBe(closeEvent)
})

test('treats an empty reason string as missing detail', () => {
const closeEvent = { code: 1011, reason: '' }
const result = normalizeChannelError(closeEvent)
expect(result.message).toBe('socket closed: 1011')
})

test('falls back to a generic transport message for plain objects', () => {
const event = { type: 'error', target: {} }
const result = normalizeChannelError(event)
expect(result.message).toBe('channel error: transport failure')
expect(result.cause).toBe(event)
})

test('returns a default Error for undefined', () => {
const result = normalizeChannelError(undefined)
expect(result).toBeInstanceOf(Error)
expect(result.message).toBe('channel error: connection lost')
})

test('returns a default Error for null', () => {
const result = normalizeChannelError(null)
expect(result).toBeInstanceOf(Error)
expect(result.message).toBe('channel error: connection lost')
})
})
Loading