Skip to content

Commit

Permalink
🎨 Enhance errorType and allow disabling it
Browse files Browse the repository at this point in the history
  • Loading branch information
elbywan committed Jun 29, 2024
1 parent b4b4645 commit cfd45a9
Show file tree
Hide file tree
Showing 5 changed files with 36 additions and 12 deletions.
4 changes: 2 additions & 2 deletions src/config.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { mix } from "./utils.js"
import type { Config } from "./types.js"
import type { Config, ErrorType } from "./types.js"

declare const global

Expand Down Expand Up @@ -94,7 +94,7 @@ export function setPolyfills(polyfills: object, replace = false) {
*
* If null, defaults to "text".
*/
export function setErrorType(errorType: string) {
export function setErrorType(errorType: ErrorType) {
config.errorType = errorType
}

Expand Down
4 changes: 2 additions & 2 deletions src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { mix, extractContentType, isLikelyJsonMime } from "./utils.js"
import { JSON_MIME, CONTENT_TYPE_HEADER, CATCHER_FALLBACK } from "./constants.js"
import { resolver } from "./resolver.js"
import config from "./config.js"
import type { Wretch } from "./types.js"
import type { Wretch, ErrorType } from "./types.js"

export const core: Wretch = {
_url: "",
Expand All @@ -16,7 +16,7 @@ export const core: Wretch = {
addon(addon) {
return { ...this, _addons: [...this._addons, addon], ...addon.wretch }
},
errorType(errorType: string) {
errorType(errorType: ErrorType) {
return {
...this,
_config: {
Expand Down
24 changes: 18 additions & 6 deletions src/resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,17 +56,29 @@ export const resolver = <T, Chain, R>(wretch: T & Wretch<T, Chain, R>) => {
err["cause"] = referenceError
err.stack = err.stack + "\nCAUSE: " + referenceError.stack
err.response = response
err.status = response.status
err.url = finalUrl

if (response.type === "opaque") {
throw err
}
return response.text().then((body: string) => {
err.message = body
if (config.errorType === "json" || response.headers.get("Content-Type")?.split(";")[0] === "application/json") {
try { err.json = JSON.parse(body) } catch (e) { /* ignore */ }

const jsonErrorType = config.errorType === "json" || response.headers.get("Content-Type")?.split(";")[0] === "application/json"
const bodyPromise =
!config.errorType ? Promise.resolve(response.body) :
jsonErrorType ? response.text() :
response[config.errorType]()

return bodyPromise.then((body: unknown) => {
err.message = typeof body === "string" ? body : response.statusText
if(body) {
if(jsonErrorType && typeof body === "string") {
err.text = body
err.json = JSON.parse(body)
} else {
err[config.errorType] = body
}
}
err.text = body
err["status"] = response.status
throw err
})
}
Expand Down
6 changes: 4 additions & 2 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ export interface Wretch<Self = unknown, Chain = unknown, Resolver = undefined> {
* @category Helpers
* @param method - The method to call on the Fetch response to read the body and use it as the Error message
*/
errorType(this: Self & Wretch<Self, Chain, Resolver>, method: string): this
errorType(this: Self & Wretch<Self, Chain, Resolver>, method: ErrorType): this

/**
* Sets non-global polyfills - for instance in browserless environments.
Expand Down Expand Up @@ -733,12 +733,14 @@ export interface WretchResponseChain<T, Self = unknown, R = undefined> {
fetchError: (this: Self & WretchResponseChain<T, Self, R>, cb: WretchErrorCallback<T, Self, R>) => this,
}

export type ErrorType = "text" | "json" | "blob" | "formData" | "arrayBuffer" | undefined | null

/**
* Configuration object.
*/
export type Config = {
options: object;
errorType: string;
errorType: ErrorType;
polyfills: object;
polyfill(p: "fetch", doThrow?: boolean): typeof fetch;
polyfill(p: "FormData", doThrow: boolean, instance: true, ...args: ConstructorParameters<typeof FormData>): FormData;
Expand Down
10 changes: 10 additions & 0 deletions test/node/wretch.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -575,6 +575,16 @@ describe("Wretch", function () {
})
.res(_ => fail("I should never be called because an error was thrown"))
.then(_ => expect(_).toBe(undefined))
// Disabled
await wretch(`${_URL}/json500raw`)
.errorType(null)
.get()
.internalError(error => {
expect(error.json).toEqual(undefined)
expect(error.text).toEqual(undefined)
})
.res(_ => fail("I should never be called because an error was thrown"))
.then(_ => expect(_).toBe(undefined))
// Global
wretch.errorType("json")
await wretch(`${_URL}/json500raw`)
Expand Down

0 comments on commit cfd45a9

Please sign in to comment.