diff --git a/src/classes/TumblrAPIError.ts b/src/classes/TumblrAPIError.ts new file mode 100644 index 0000000..332eb34 --- /dev/null +++ b/src/classes/TumblrAPIError.ts @@ -0,0 +1,13 @@ +import { TumblrAPIResponse } from "../interfaces"; + +export class TumblrAPIError extends Error { + public response: TumblrAPIResponse; + public queryURL: string; + + constructor(message: TumblrAPIResponse, queryURL: string) { + super(`${message.meta.status}: ${message.meta.msg}`); + this.name = "TumblrAPIError"; + this.response = message; + this.queryURL = queryURL; + } +} diff --git a/src/classes/index.ts b/src/classes/index.ts new file mode 100644 index 0000000..ad398fc --- /dev/null +++ b/src/classes/index.ts @@ -0,0 +1 @@ +export * from "./TumblrAPIError"; diff --git a/src/functions/AccessTumblrApi.ts b/src/functions/AccessTumblrApi.ts index 6d452d3..45ede59 100644 --- a/src/functions/AccessTumblrApi.ts +++ b/src/functions/AccessTumblrApi.ts @@ -1,3 +1,4 @@ +import { TumblrAPIError } from "../classes"; import { TumblrAPIResponse } from "../interfaces"; /** @@ -35,5 +36,9 @@ export async function accessTumblrAPI( const response: TumblrAPIResponse = await request.json(); + if (!request.ok) { + throw new TumblrAPIError(response, url); + } + return response; } diff --git a/src/index.ts b/src/index.ts index e7176cd..454bbf9 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,2 +1,3 @@ +export * from "./classes"; export * from "./functions"; export * from "./interfaces"; diff --git a/tests/Api.test.ts b/tests/Api.test.ts index 183d1cf..359f18d 100644 --- a/tests/Api.test.ts +++ b/tests/Api.test.ts @@ -1,10 +1,15 @@ -import { accessTumblrAPI } from "../src"; +import { accessTumblrAPI, TumblrAPIError } from "../src"; const token = process.env.TUMBLR_TOKEN; if (!token) throw new Error("No token provided"); it("should error on invalid path", async () => { - const response = await accessTumblrAPI(token, "invalid/path"); - expect(response.meta.status).toBe(404); + const error = await accessTumblrAPI(token, "invalid/path").catch(e => e); + expect(error instanceof TumblrAPIError).toBe(true); + if (error instanceof TumblrAPIError) { + expect(error.response.meta.status).toBe(404); + expect(error.response.meta.msg).toBe("Not Found"); + expect(error.queryURL).toBe("https://api.tumblr.com/v2/invalid/path?"); + } });