Skip to content

Commit

Permalink
Merge pull request #110 from local-first-web/handle-connection-errors
Browse files Browse the repository at this point in the history
Add error handling to the Connection state machine
  • Loading branch information
HerbCaudill committed May 23, 2024
2 parents 9945e99 + ff32ee2 commit 1463003
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
15 changes: 11 additions & 4 deletions packages/auth/src/connection/Connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
TIMEOUT,
createErrorMessage,
type ConnectionErrorType,
UNHANDLED,
} from 'connection/errors.js'
import { getDeviceUserFromGraph } from 'connection/getDeviceUserFromGraph.js'
import * as identity from 'connection/identity.js'
Expand Down Expand Up @@ -694,10 +695,16 @@ export class Connection extends EventEmitter<ConnectionEvents> {
this.#machine = createActor(machine)

// emit and log all transitions
this.#machine.subscribe(state => {
const summary = stateSummary(state.value as string)
this.emit('change', summary)
this.#log(`⏩ ${summary} `)
this.#machine.subscribe({
next: state => {
const summary = stateSummary(state.value as string)
this.emit('change', summary)
this.#log(`⏩ ${summary} `)
},
error: error => {
console.error('Connection encountered an unhandled error', error)
this.#fail(UNHANDLED)
},
})

// add automatic logging to all events
Expand Down
4 changes: 4 additions & 0 deletions packages/auth/src/connection/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export const MEMBER_REMOVED = 'MEMBER_REMOVED' as const
export const NEITHER_IS_MEMBER = 'NEITHER_IS_MEMBER' as const
export const SERVER_REMOVED = 'SERVER_REMOVED' as const
export const TIMEOUT = 'TIMEOUT' as const
export const UNHANDLED = 'UNHANDLED' as const

export const connectionErrors: Record<string, ErrorDefinition> = {
[DEVICE_REMOVED]: {
Expand Down Expand Up @@ -48,6 +49,9 @@ export const connectionErrors: Record<string, ErrorDefinition> = {
localMessage: "We didn't hear back from the peer; giving up",
remoteMessage: "The peer didn't hear back from you, so they gave up",
},
[UNHANDLED]: {
localMessage: 'An unhandled error occurred',
},
}

/** Creates an error payload with an appropriate message for the local or remote user */
Expand Down

0 comments on commit 1463003

Please sign in to comment.