Skip to content

Commit 473c46b

Browse files
authored
Improve error insight for twirp related requests (#390)
* Improve error insight for twirp related requests * account for non json response * rename status * catch parsing errors * Create gentle-panthers-guess.md * cleanup
1 parent 697a444 commit 473c46b

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

Diff for: .changeset/gentle-panthers-guess.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"livekit-server-sdk": minor
3+
---
4+
5+
Improve error insight for twirp related requests, changes the error signature to custom TwirpError

Diff for: packages/livekit-server-sdk/src/TwirpRPC.ts

+34-1
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,18 @@ export interface Rpc {
1313
request(service: string, method: string, data: JsonValue, headers?: any): Promise<string>;
1414
}
1515

16+
export class TwirpError extends Error {
17+
status: number;
18+
code?: string;
19+
20+
constructor(name: string, message: string, status: number, code?: string) {
21+
super(message);
22+
this.name = name;
23+
this.status = status;
24+
this.code = code;
25+
}
26+
}
27+
1628
/**
1729
* JSON based Twirp V7 RPC
1830
*/
@@ -47,9 +59,30 @@ export class TwirpRpc {
4759
});
4860

4961
if (!response.ok) {
50-
throw new Error(`Request failed with status ${response.status}: ${response.statusText}`);
62+
const isJson = response.headers.get('content-type') === 'application/json';
63+
let errorMessage = 'Unknown internal error';
64+
let errorCode: string | undefined = undefined;
65+
try {
66+
if (isJson) {
67+
const parsedError = (await response.json()) as Record<string, unknown>;
68+
if ('msg' in parsedError) {
69+
errorMessage = <string>parsedError.msg;
70+
}
71+
if ('code' in parsedError) {
72+
errorCode = <string>parsedError.code;
73+
}
74+
} else {
75+
errorMessage = await response.text();
76+
}
77+
} catch (e) {
78+
// parsing went wrong, no op and we keep default error message
79+
console.debug(`Error when trying to parse error message, using defaults`, e);
80+
}
81+
82+
throw new TwirpError(response.statusText, errorMessage, response.status, errorCode);
5183
}
5284
const parsedResp = (await response.json()) as Record<string, unknown>;
85+
5386
const camelcaseKeys = await import('camelcase-keys').then((mod) => mod.default);
5487
return camelcaseKeys(parsedResp, { deep: true });
5588
}

0 commit comments

Comments
 (0)