Skip to content

Commit

Permalink
Improve error insight for twirp related requests (#390)
Browse files Browse the repository at this point in the history
* Improve error insight for twirp related requests

* account for non json response

* rename status

* catch parsing errors

* Create gentle-panthers-guess.md

* cleanup
  • Loading branch information
lukasIO authored Jan 25, 2025
1 parent 697a444 commit 473c46b
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/gentle-panthers-guess.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"livekit-server-sdk": minor
---

Improve error insight for twirp related requests, changes the error signature to custom TwirpError
35 changes: 34 additions & 1 deletion packages/livekit-server-sdk/src/TwirpRPC.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,18 @@ export interface Rpc {
request(service: string, method: string, data: JsonValue, headers?: any): Promise<string>;
}

export class TwirpError extends Error {
status: number;
code?: string;

constructor(name: string, message: string, status: number, code?: string) {
super(message);
this.name = name;
this.status = status;
this.code = code;
}
}

/**
* JSON based Twirp V7 RPC
*/
Expand Down Expand Up @@ -47,9 +59,30 @@ export class TwirpRpc {
});

if (!response.ok) {
throw new Error(`Request failed with status ${response.status}: ${response.statusText}`);
const isJson = response.headers.get('content-type') === 'application/json';
let errorMessage = 'Unknown internal error';
let errorCode: string | undefined = undefined;
try {
if (isJson) {
const parsedError = (await response.json()) as Record<string, unknown>;
if ('msg' in parsedError) {
errorMessage = <string>parsedError.msg;
}
if ('code' in parsedError) {
errorCode = <string>parsedError.code;
}
} else {
errorMessage = await response.text();
}
} catch (e) {
// parsing went wrong, no op and we keep default error message
console.debug(`Error when trying to parse error message, using defaults`, e);
}

throw new TwirpError(response.statusText, errorMessage, response.status, errorCode);
}
const parsedResp = (await response.json()) as Record<string, unknown>;

const camelcaseKeys = await import('camelcase-keys').then((mod) => mod.default);
return camelcaseKeys(parsedResp, { deep: true });
}
Expand Down

0 comments on commit 473c46b

Please sign in to comment.