Skip to content

Commit

Permalink
feat: Use API error messages when throwing errors, whenever possible. (
Browse files Browse the repository at this point in the history
  • Loading branch information
dlxmj authored Feb 19, 2024
1 parent 97bd3eb commit 4873515
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
19 changes: 18 additions & 1 deletion src/client.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, it, expect } from "vitest";
import { TursoClient, createClient } from "./client";
import { TursoClient, TursoClientError, createClient } from "./client";

describe("TursoClient", () => {
it("should throw an error if no API token is provided", () => {
Expand All @@ -17,6 +17,23 @@ describe("TursoClient", () => {

expect(client).toBeInstanceOf(TursoClient);
});

it("should throw an error message that will match with API's error message", async () => {
const config = { org: "turso", token: "abc" };
const client = new TursoClient(config);

const error = await client.databases
.get("databaseName")
.catch((err: Error) => err);

expect(error).toBeInstanceOf(TursoClientError);
if (error instanceof TursoClientError) {
expect(error.message).toBe(
"token contains an invalid number of segments"
);
expect(error.status).toBe(401);
}
});
});

describe("createClient", () => {
Expand Down
25 changes: 24 additions & 1 deletion src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,23 @@ import { LocationClient } from "./location";
import { GroupClient } from "./group";
import { DatabaseClient } from "./database";

interface ApiErrorResponse {
error: string;
}

interface AdditionalInfo {
status?: number;
}

export class TursoClientError extends Error {
status?: number;
constructor(message: string, additionalInfo?: AdditionalInfo) {
super(message);
this.name = "TursoClientError";
this.status = additionalInfo?.status;
}
}

export class TursoClient {
private config: TursoConfig;
public apiTokens: ApiTokenClient;
Expand Down Expand Up @@ -45,7 +62,13 @@ export class TursoClient {
});

if (!response.ok) {
throw new Error(`Something went wrong! Status ${response.status}`);
const errorResponse = (await response.json().catch(() => {
throw new Error(`Something went wrong! Status ${response.status}`);
})) as ApiErrorResponse;

throw new TursoClientError(errorResponse.error, {
status: response.status,
});
}

return response.json() as T;
Expand Down

0 comments on commit 4873515

Please sign in to comment.