type InterceptorResponse = Omit< typeof Response.prototype, 'text' | 'formData' | 'blob' | 'json' | 'arrayBuffer' > type FetchInterceptorResponseConfig = { onUnauthenticated?: (obj: InterceptorResponse) => void onInternalError?: (obj: InterceptorResponse) => void onForbidden?: (obj: InterceptorResponse) => void onRateLimit?: (obj: InterceptorResponse) => void } type FetchResponseType = "text" | "json" | "blob" | "arrayBuffer" type FetchInterceptorArgs = { config: FetchInterceptorResponseConfig, responseTypes: FetchResponseType[] } function createFetchResponseInterceptor({ config, responseTypes }: FetchInterceptorArgs) { const createInterceptor = (responseType: FetchResponseType) => { return new Proxy(Response.prototype[responseType], { apply(target: any, obj: any, args: any) { const response: string | object | ArrayBuffer | Blob | FormData = target.call(obj, args) if (obj.status === 401 && config.onUnauthenticated) { config.onUnauthenticated(obj) } if (obj.status === 403 && config.onForbidden) { config.onForbidden(obj) } if (obj.status === 500 && config.onInternalError) { config.onInternalError(obj) } if (obj.status === 502 && config.onRateLimit) { config.onRateLimit(obj) } return response }, }) } return responseTypes.map(responseType => createInterceptor(responseType)) } /* Using interceptor */ ;(async () => { const [text, json, blob, arrayBuffer] = createFetchResponseInterceptor({ config: { onUnauthenticated: obj => { console.log(`Signing out because it's not authenticated`) // do sign out... }, onForbidden: obj => { console.log(`User has not permissions to access to this resource.`) // do something else if you want... }, onInternalError: obj => { console.log(`Something went wrong at server side`) // do something else if you want... }, }, responseTypes: ["text", "json", "blob", "arrayBuffer"] }) try { Response.prototype.text = text Response.prototype.json = json Response.prototype.blob = blob Response.prototype.arrayBuffer = arrayBuffer Object.freeze(Response.prototype) } catch {} const statusCodes = [200, 401, 403, 500] for (const statusCode of statusCodes) { const res = await fetch(`https://httpstat.us/${statusCode}`); const body = await res.text(); if (res.ok) { console.log("Server responded with: ", body) } } })()