feat: better mapping for WS errors

This commit is contained in:
Adhiraj Singh
2023-01-17 22:01:51 +05:30
parent f54e8f8813
commit c24ffc1bed
2 changed files with 22 additions and 9 deletions

View File

@@ -97,7 +97,7 @@ export const makeSocket = ({
const result = promiseTimeout<any>(connectTimeoutMs, (resolve, reject) => {
onOpen = (data: any) => resolve(data)
onClose = reject
onClose = mapWebSocketError(reject)
ws.on('frame', onOpen)
ws.on('close', onClose)
ws.on('error', onClose)
@@ -335,7 +335,7 @@ export const makeSocket = ({
let onClose: (err: Error) => void
await new Promise((resolve, reject) => {
onOpen = () => resolve(undefined)
onClose = reject
onClose = mapWebSocketError(reject)
ws.on('open', onOpen)
ws.on('close', onClose)
ws.on('error', onClose)
@@ -433,12 +433,7 @@ export const makeSocket = ({
end(err)
}
})
ws.on('error', error => end(
new Boom(
`WebSocket Error (${error.message})`,
{ statusCode: getCodeFromWSError(error), data: error }
)
))
ws.on('error', mapWebSocketError(end))
ws.on('close', () => end(new Boom('Connection Terminated', { statusCode: DisconnectReason.connectionClosed })))
// the server terminated the connection
ws.on('CB:xmlstreamend', () => end(new Boom('Connection Terminated by Server', { statusCode: DisconnectReason.connectionClosed })))
@@ -604,4 +599,19 @@ export const makeSocket = ({
}
}
/**
* map the websocket error to the right type
* so it can be retried by the caller
* */
function mapWebSocketError(handler: (err: Error) => void) {
return (error: Error) => {
handler(
new Boom(
`WebSocket Error (${error.message})`,
{ statusCode: getCodeFromWSError(error), data: error }
)
)
}
}
export type Socket = ReturnType<typeof makeSocket>

View File

@@ -353,7 +353,10 @@ export const getCodeFromWSError = (error: Error) => {
if(!Number.isNaN(code) && code >= 400) {
statusCode = code
}
} else if((error as any).code?.startsWith('E')) { // handle ETIMEOUT, ENOTFOUND etc
} else if(
(error as any).code?.startsWith('E')
|| error?.message?.includes('timed out')
) { // handle ETIMEOUT, ENOTFOUND etc
statusCode = 408
}