Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve error insight for twirp related requests #390

Merged
merged 6 commits into from
Jan 25, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading