Skip to content

Commit 4873515

Browse files
authored
feat: Use API error messages when throwing errors, whenever possible. (#13)
1 parent 97bd3eb commit 4873515

2 files changed

Lines changed: 42 additions & 2 deletions

File tree

src/client.test.ts

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { describe, it, expect } from "vitest";
2-
import { TursoClient, createClient } from "./client";
2+
import { TursoClient, TursoClientError, createClient } from "./client";
33

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

1818
expect(client).toBeInstanceOf(TursoClient);
1919
});
20+
21+
it("should throw an error message that will match with API's error message", async () => {
22+
const config = { org: "turso", token: "abc" };
23+
const client = new TursoClient(config);
24+
25+
const error = await client.databases
26+
.get("databaseName")
27+
.catch((err: Error) => err);
28+
29+
expect(error).toBeInstanceOf(TursoClientError);
30+
if (error instanceof TursoClientError) {
31+
expect(error.message).toBe(
32+
"token contains an invalid number of segments"
33+
);
34+
expect(error.status).toBe(401);
35+
}
36+
});
2037
});
2138

2239
describe("createClient", () => {

src/client.ts

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,23 @@ import { LocationClient } from "./location";
55
import { GroupClient } from "./group";
66
import { DatabaseClient } from "./database";
77

8+
interface ApiErrorResponse {
9+
error: string;
10+
}
11+
12+
interface AdditionalInfo {
13+
status?: number;
14+
}
15+
16+
export class TursoClientError extends Error {
17+
status?: number;
18+
constructor(message: string, additionalInfo?: AdditionalInfo) {
19+
super(message);
20+
this.name = "TursoClientError";
21+
this.status = additionalInfo?.status;
22+
}
23+
}
24+
825
export class TursoClient {
926
private config: TursoConfig;
1027
public apiTokens: ApiTokenClient;
@@ -45,7 +62,13 @@ export class TursoClient {
4562
});
4663

4764
if (!response.ok) {
48-
throw new Error(`Something went wrong! Status ${response.status}`);
65+
const errorResponse = (await response.json().catch(() => {
66+
throw new Error(`Something went wrong! Status ${response.status}`);
67+
})) as ApiErrorResponse;
68+
69+
throw new TursoClientError(errorResponse.error, {
70+
status: response.status,
71+
});
4972
}
5073

5174
return response.json() as T;

0 commit comments

Comments
 (0)