|
1 | 1 | import type { ActionTree } from 'vuex' |
2 | 2 | import { consola } from 'consola' |
3 | | -import type { SocketState, SocketStatus } from './types' |
| 3 | +import type { SocketError, SocketState, SocketStatus } from './types' |
4 | 4 | import type { RootState } from '../types' |
5 | 5 | import { Globals } from '@/globals' |
6 | 6 | import { SocketActions } from '@/api/socketActions' |
@@ -30,6 +30,27 @@ const VALID_TRANSITIONS: Record<SocketStatus, readonly SocketStatus[]> = { |
30 | 30 | ready: ['disconnected', 'connecting', 'authenticating'] |
31 | 31 | } |
32 | 32 |
|
| 33 | +const tryGetErrorMessageFromJson = (message: string): string | null => { |
| 34 | + try { |
| 35 | + // If our message contains JSON, we should try to parse it. |
| 36 | + // This was a problem in old versions of Moonraker, not sure if it's still the case, but it doesn't hurt to be defensive here. |
| 37 | + const messageAsObject = JSON.parse(message.replace(/'/g, '"')) |
| 38 | + |
| 39 | + if ( |
| 40 | + messageAsObject !== null && |
| 41 | + typeof messageAsObject === 'object' && |
| 42 | + 'message' in messageAsObject && |
| 43 | + typeof messageAsObject.message === 'string' |
| 44 | + ) { |
| 45 | + return messageAsObject.message |
| 46 | + } |
| 47 | + } catch { |
| 48 | + // ignore and assume it's a plain string |
| 49 | + } |
| 50 | + |
| 51 | + return null |
| 52 | +} |
| 53 | + |
33 | 54 | const getMoonrakerDatabase = async <T = Record<string, unknown>>(namespace: string) => { |
34 | 55 | try { |
35 | 56 | const response = await SocketActions.serverDatabaseGetItem<T>(undefined, namespace) |
@@ -258,18 +279,16 @@ export const actions = { |
258 | 279 | * Fired when the socket encounters an error. ws.onclose always follows and |
259 | 280 | * drives the transition; here we just surface RPC error codes. |
260 | 281 | */ |
261 | | - async onSocketError ({ state, commit }, payload) { |
262 | | - if (state.status === 'ready' && payload.code >= 400 && payload.code < 500) { |
263 | | - // If our message contains json, we should try to parse it. |
264 | | - // This is pretty bad, should get moonraker to fix this response. |
265 | | - let message = '' |
266 | | - try { |
267 | | - const messageAsObject = JSON.parse(payload.message.replace(/'/g, '"')) as { message: string } |
268 | | - |
269 | | - message = messageAsObject.message |
270 | | - } catch { |
271 | | - message = payload.message |
272 | | - } |
| 282 | + async onSocketError ({ state, commit }, payload: SocketError) { |
| 283 | + if ( |
| 284 | + state.status === 'ready' && |
| 285 | + payload.code >= 400 && |
| 286 | + payload.code < 500 |
| 287 | + ) { |
| 288 | + const message = ( |
| 289 | + tryGetErrorMessageFromJson(payload.message) || |
| 290 | + payload.message |
| 291 | + ) |
273 | 292 |
|
274 | 293 | EventBus.$emit(message, { type: 'error' }) |
275 | 294 | } else if (payload.code === 503) { |
|
0 commit comments