add fetch errors

This commit is contained in:
DrakeTDL 2023-10-12 00:53:37 -07:00
parent 7e7e3c5378
commit 9d0ef7b579
No known key found for this signature in database
4 changed files with 44 additions and 6 deletions

View File

@ -53,6 +53,8 @@ import { AniChartUser } from "./queries/AniChartUser.ts"
import { Markdown } from "./queries/Markdown.ts"
import { SiteStatistics } from "./queries/SiteStatistics.ts"
import { ExternalLinkSourceCollection } from "./queries/ExternalLinkSourceCollection.ts"
import { AuthorizationError } from "./utils/AuthorizationError.ts"
import { ResponseError } from "./utils/ResponseError.ts"
const rewriteVarValues = (
variable: PropertyKey | unknown | (PropertyKey | unknown)[],
@ -141,15 +143,16 @@ const fetch: Fetch = async (init) => {
Object.assign(body, { query })
if (token) headers.set("Authorization", `Bearer ${token}`)
}
const res = await self.fetch(host, {
method: "POST",
headers,
body: JSON.stringify(body),
})
if (res.status !== 200) {
throw new Error("Something went wrong.", {
cause: JSON.stringify(await res.json()),
})
if ("code" in init) throw new AuthorizationError(await res.json())
throw new ResponseError(await res.json())
}
return await res.json()
}

View File

@ -1,3 +1,6 @@
import { type AuthorizationError } from "../utils/AuthorizationError.ts"
import { ResponseError } from "../utils/ResponseError.ts"
export type Fields<in Q extends (...args: any) => any> = {
query: ReturnType<Q>[]
level: number
@ -44,12 +47,11 @@ export type Fetch = {
string
>
& { "grant_type"?: "authorization_code" },
): Promise<Authorization>
): Promise<Authorization | AuthorizationError>
(
init: { query: string; token?: string },
): Promise<Response>
): Promise<Response | ResponseError>
}
export type Response<T = Record<string, any>> = {
data: T
}

View File

@ -0,0 +1,13 @@
export type AuthorizationError = { error: string; message: string; hint?: string }
export const AuthorizationError = class extends Error {
hint?: string
constructor(message: AuthorizationError) {
super()
this.name = "AuthorizationError"
this.message = message.error
this.cause = message.message
this.hint = message.hint
}
}

View File

@ -0,0 +1,20 @@
export type ResponseError = {
errors: Array<{
message: string
status: number
locations: Array<Record<"line" | "column", number>>
}>
data: Record<string, unknown>
}
export const ResponseError = class extends Error {
errors: ResponseError["errors"]
data: ResponseError["data"]
constructor(message: ResponseError) {
super()
this.name = "ResponseError"
this.errors = message.errors
this.data = message.data
}
}